Bài giảng Lập trình Java - Trần Anh Dũng - Chương 2: Cơ bản về ngôn ngữ Java

 Biến & Hằng

 Kiểu dữliệu

 Toán tử, biểu thức

 Các cấu trúc ñiều khiển (chọn, rẽnhánh, lặp)

 Lớp bao kiểu cơsở

 Phương thức và cách sửdụng

 Một sốlớp cơbản

pdf59 trang | Chuyên mục: Java | Chia sẻ: dkS00TYs | Lượt xem: 2623 | Lượt tải: 2download
Tóm tắt nội dung Bài giảng Lập trình Java - Trần Anh Dũng - Chương 2: Cơ bản về ngôn ngữ Java, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
for ( int i=1; i<=100; i+=2)
tong+=i;
System.out.println(“Tong = ” + tong);
}
}
Ví dụ - Cấu trúc lặp
28
// Tính tổng các số lẻ từ 1 ñến 100
int tong = 0, i = 1;
while (i<=100)
{
tong+=i;
i+=2;
}
System.out.println(“Tong = “ + tong);
Ví dụ - Cấu trúc lặp
29
 break
 continue
 label: Java dùng kết hợp nhãn (label) với từ khóa break và
continue ñể thay thế cho lệnh goto.
label1:
for (…)
{ for (…)
{ if ()
break label1;
else
continue label1;
}
}
Cấu trúc lệnh nhảy
30
Cấu trúc lệnh nhảy – Ví dụ 1
import javax.swing.JOptionPane;
public class BreakTest{
public static void main( String args[] ){
String output = "";
int count; 
for ( count = 1; count <= 10; count++ ){
if ( count == 5 )
break; // terminate loop
output += count + " ";
}
………………
31
………….
output += "\nBroke out of loop at count = " + count;
JOptionPane.showMessageDialog( null, 
output, "Thong bao", 
JOptionPane.INFORMATION_MESSAGE);
System.exit( 0 ); // terminate application
} 
}
Cấu trúc lệnh nhảy – Ví dụ 1
32
import javax.swing.JOptionPane; 
public class ContinueTest{ 
public static void main( String args[] ){
String output = "";
for ( int count = 1; count <= 10; count++ ) { 
if ( count == 5 ) // if count is 5,
continue; // skip remaining code in loop
output += count + " ";
}
output += "\nUsed continue to skip printing 5";
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
}
}
Cấu trúc lệnh nhảy – Ví dụ 2
33
Cấu trúc lệnh nhảy – Ví dụ 2
34
[t]
[f]
[f]
[t]
break
break
[t]
break
[t]
[f]
[t]
[f]
[t]
[f]
[t]
[f]
Repetition
while statement do while statement for statement
SelectionSequence
if else statement (double selection)
if statement (single selection) switch statement (multiple 
selection)
.
.
.
[t][f]
default
35
 Tồn tại các lớp ñối tượng tương ứng
Lớp bao kiểu dữ liệu cơ sở
Data type Wrapper Class 
(java.lang.*)
Ghi chú
boolean Boolean - Gói (package): chứa nhóm 
nhiều class.
- Ngoài các Wrapper Class,
gói java.lang còn cung cấp các
lớp nền tảng cho việc thiết kế
ngôn ngữ java như: String,
Math, …
byte Byte
short Short
char Character
int Integer
long Long
float Float
double Double
36
 Các lớp dữ liệu nguyên thủy cung cấp:
 Các phương thức tiện ích:
 valueOf(String s): Trả ñối tượng thuộc kiểu tương
ứng
 static parseType(String s): Trả giá trị nguyên thủy
tương ứng
 Hằng số:
 Type.MAX_VALUE, Type.MIN_VALUE
 Type.POSITIVE_INFINITY, Type.NEGATIVE_INFINITY
Một số lớp cơ sở
37
class tong {
public static void main (String args[])
{
int i=0;
int tong=0;
for (i=0; i<args.length; i++) 
tong += Integer.parseInt(args[i]);
System.out.print(“Tong = ” + tong);
}
}
Ví dụ - Lớp bao kiểu dữ liệu cơ sở
38
 Cung cấp một số phương thức:
 static boolean isUppercase(char ch)
 static boolean isLowercase(char ch)
 static boolean isDigit(char ch)
 static boolean isLetter(char ch)
 static boolean isLetterOrDigit(char ch)
 static char toUpperCase(char ch)
 static char toLowerCase(char ch)
Một số lớp cơ sở - Lớp Character
39
 Hằng số:
 Math.E
 Math.PI
 Các phương thức:
 type abs(type)
 double ceil(double), double floor(double)
 int round(float), long round(double)
 type max(type, type), type min(type, type)
 double random(): Sinh số ngẫu nhiên trong ñoạn [0.0,1.0]
Một số lớp cơ sở - Lớp Math
40
 Lũy thừa:
 double pow(double, double)
 double log(double)
 double sqrt(double)
 Lượng giác:
 double sin(double)
 double cos(double)
 double tan(double)
Một số lớp cơ sở - Lớp Math
41
 Nằm trong gói java.util
 Cung cấp 4 phương thức static ñể làm việc với mảng
 fill(): khởi tạo các phần tử của mảng với một giá trị như
nhau
 sort(): xắp xếp mảng
 equals(): so sánh hai mảng
 binarySearch(): tìm kiếm nhị phân trên mảng ñã sắp
xếp
Một số lớp cơ sở - Lớp Arrays
42
 Khởi tạo:
 String (String)
 String (StringBuffer)
 String (byte[])
 String (char[])
 ……
 Phương thức:
 int length(): kích thước của xâu
 char charAt(int index): ký tự ở vị trí index
 boolean equals(String)
 boolean equalsIgnoreCase(String)
 boolean startWith(String)
 boolean endWith(String)
 int compareTo(String)
Một số lớp cơ sở - Lớp String
43
 Phương trức chuyển ñổi:
 String toUpperCase()
 String toLowerCase()
Ghép xâu:
 String concat(String)
 Toán tử “+”
 Trích xâu:
 String trim(): loại bỏ ký tự trắng
 String substring(int startIndex)
 String substring(int startIdx, int endIdx)
Một số lớp cơ sở - Lớp String
44
 Phương thức tìm kiếm:
 int indexOf(char)
 int indexOf(char ch, int from)
 int indexOf(String)
 int indexOf(String s, int from)
 int lastIndexOf(char)
 int lastIndexOf(char, int)
 int lastIndexOf(String)
 int lastIndexOf(String, int)
 Phương thức thay thế:
 String replace(char ch, char new_ch)
Một số lớp cơ sở - Lớp String
45
 Strings in Java once created cannot be changed directly
Một số lớp cơ sở - Lớp String
class Testing{
public static void main(String[] args){
String str = "Hello";
str.concat("And Goodbye");
System.out.println(str);
}
}
Output
46
 A StringBuffer is used to represent a string that can be
modified.
Một số lớp cơ sở - Lớp StringBuffer
class ConcatDemo{
public static void main(String[] args){
String str = "Hello";
StringBuffer sbObj = new StringBuffer(str);
str = sbObj.append(" And Goodbye").toString();
System.out.println(str);
}
}
Output
47
 Khởi tạo:
 StringBuffer(String)
 StringBuffer(int length)
 StringBuffer(): ñặt kích thước mặc ñịnh 16
 Các phương thức:
 int length(), void setLength(int length)
 char charAt(int index)
 void setCharAt(int index, char ch)
 String toString()
Một số lớp cơ sở - Lớp StringBuffer
48
 Phương thức thêm xóa:
 append(String), …
 insert(int offset, String s)
 insert(int offset, char[] chs), …
 delete(int start, int end): xóa xâu con
 delete(int index): xóa một ký tự
 reverse(): ñảo ngược
Một số lớp cơ sở - Lớp StringBuffer
49
Lớp Date
Constructor Purpose
Date( ) Creates a Date using today’s date.
Date(long dt) Creates a Date using the specified number of
milliseconds since January 1, 1970.
Date( int year, 
int month, int day)
Creates a Date using the specified year, month
and day.
50
Lớp Date – Ví dụ
import java.util.*;
import java.text.*;
class DateTime{
public static void main(String args[]){
String strDate, strTime = "";
SimpleDateFormat sdfFormat;
DateFormatSymbols dfsLocales;
//Create a US English locale 
dfsLocales = new DateFormatSymbols(new
Locale("en","US"));
//Create a pattern to format the date
//as per the US English locale
sdfFormat = new SimpleDateFormat("yyyy.MMMMM.dd GGG 
'at' hh:mm:ss aaa", dfsLocales);
//current date is obtained
Date objDate = new Date();
strDate = objDate.toString();
System.out.println("Current Date :" + strDate);
System.out.println("After formatting " + 
sdfFormat.format(objDate));
//Extract GMT time
strTime = strDate.substring(11,( strDate.length()-4)); 
//Extract the time in hours, minutes, seconds
strTime = "Time : " + strTime.substring(0,8); 
System.out.println(strTime);
}
} Output
51
Lớp Calendar
import java.util.*;
class DateTimeComponents{
public static void main(String [] args){
Calendar objCalendar = Calendar.getInstance();
//Display the Date and Time components
System.out.println("\nDate and Time components:");
System.out.println("Month : 
"+objCalendar.get(Calendar.MONTH));
System.out.println("Day : 
"+objCalendar.get(Calendar.DATE)); 
System.out.println("Year : 
"+objCalendar.get(Calendar.YEAR));
System.out.println("Hour : " + 
objCalendar.get(Calendar.HOUR));
System.out.println("Minute : " + 
objCalendar.get(Calendar.MINUTE));
System.out.println("Second : " + 
objCalendar.get(Calend r.SECOND));
Add 30 minutes to current ti e, 
//th n display date a d ime
objCalendar.add(Calendar.MINUTE,30);
Date objDate = objCalendar.getTime );
\nDate and Time after adding 30 
mi utes to current time:\n");
objDate);
}
}
Output
52
 Used for memory management and executing additional
processes.
We can determine memory allocation details by using
totalMemory() and freeMemory() methods
Lớp Runtime
53
Lớp Runtime – Ví dụ
class RuntimeDemo{
public static void main(String[] args){
try {
Runtime Objrun = Runtime.getRuntime();
Process Objprocess = null;
Objprocess = Objrun.exec("calc.exe");
}
catch (Exception ex){
}
}
}
Output
54
1. Viết chương trình tạo một mảng số nguyên ngẫu nhiên
có n phần tử
a) Xuất giá trị các phần tử của mảng.
b) Tìm phần tử có giá trị lớn nhất, nhỏ nhất.
c) Tính tổng giá trị của các phần tử là số nguyên tố.
d) ðếm số phần tử có tổng các chữ số lớn hơn 10.
e) Sắp xếp mảng tăng dần/giảm dần
f ) Sắp xếp số chẵn giảm dần, số lẻ tăng dần
g) Tìm phần tử có giá trị x
Bài tập
55
2. Cho ma trận số nguyên cấp n x m. Cài ñặt các hàm thực
hiện các chức năng sau:
a) Nhập ma trận.
b) In ma trận.
c) Tìm phần tử nhỏ nhất.
d) Tìm phần tử lẻ lớn nhất.
e) Tìm dòng có tổng lớn nhất.
f ) Tính tổng các số không phải là số nguyên tố.
Bài tập
56
3. Cho ma trận vuông số nguyên cấp n. Cài ñặt các hàm
thực hiện các chức năng sau:
a) Nhập ma trận.
b) In ma trận.
c) Tổng các phần tử thuộc tam giác trên.
d) Tổng các phần tử thuộc tam giác dưới.
e) Kiểm tra xem ma trận có ñối xứng qua ñường chéo
chính?
Bài tập
57
 java.lang
 java.applet
 java.awt
 java.io
 java.util
 java.net
 java.awt.event
 java.rmi
 java.security
 java.sql
Các gói chuẩn của Java
58
Từ khóa của Java
Danh sách từ khóa thường gặp
abstract else interface super
boolean extends long switch
break false native synchronized
byte final new this
case finally null throw
catch float package throws
char for private true
class goto protected try
continue if public void
default implements return while
do import short enum
double instanceof static …
59
Hỏi & ñáp

File đính kèm:

  • pdfBài giảng Lập trình Java - Trần Anh Dũng - Chương 2_Cơ bản về ngôn ngữ Java.pdf
Tài liệu liên quan