Mục tiêu bài học:
- Sử dụng các phương thức xuất dữ liệu:
print(),println(),printf() - Sử dụng lớp
Scannerđể nhập dữ liệu từ bàn phím - Định dạng đầu ra với các specifier (
PT s,PT d,PT f,PT c)- PT là ký hiệu phần trăm trên bàn phím
- Xử lý ngoại lệ cơ bản khi nhập liệu
- Đọc và ghi file văn bản cơ bản
Phần 1: Xuất dữ liệu ra màn hình
1.1. Các phương thức xuất dữ liệu cơ bản
Cú pháp:
System.out.print(dữ_liệu); // In ra dữ liệu, không xuống dòng
System.out.println(dữ_liệu); // In ra dữ liệu, có xuống dòng
System.out.println(); // Chỉ xuống dòngTham số:
dữ_liệu: Có thể là bất kỳ kiểu dữ liệu nào (số, chuỗi, đối tượng…)
Ví dụ:
public class OutputBasic {
public static void main(String[] args) {
// In không xuống dòng
System.out.print("Xin chào ");
System.out.print("Java!");
// Kết quả: Xin chào Java!
// In và xuống dòng
System.out.println("Dòng 1");
System.out.println("Dòng 2");
// Kết quả:
// Dòng 1
// Dòng 2
// Xuống dòng rỗng
System.out.println();
System.out.println("Sau dòng trống");
}
}1.2. Định dạng đầu ra với printf()
Cú pháp:
System.out.printf("chuỗi định dạng", tham_số_1, tham_số_2, ...);Các định dạng specifier:
| Specifier | Kiểu dữ liệu | Ví dụ |
|---|---|---|
PTs | String | " → “Hello” |
| số nguyên (decimal) | " → 123 |
| số thực (floating) | " → 3.14 |
| ký tự (character) | " → ‘A’ |
| boolean | " → true/false |
| xuống dòng | " → new line |
Cú pháp chi tiết:
PT[flags][width][.precision]conversion-characterVí dụ:
// Chú ý, code dưới đây, hãy thay thế "PT" - ký hiệu phần trăm
public class PrintfDemo {
public static void main(String[] args) {
String name = "Nguyễn Văn A";
int age = 25;
double salary = 15000000.5678;
// Cơ bản
System.out.printf("Tên: PTs, Tuổi: PTd, Lương: PT.2fPTn", name, age, salary);
// Căn lề trái/phải
System.out.printf("|PT-20s|PT10d|PT15.2f|PTn", name, age, salary);
// Thêm số 0 đằng trước
System.out.printf("Số điện thoại: PT010dPTn", 912345678);
// Định dạng tiền tệ
System.out.printf("Lương: PT,.2f VNDPTn", salary);
// Ngày tháng
System.out.printf("Ngày: PTtFPTn", new java.util.Date());
}
}Phần 2: Nhập dữ liệu từ bàn phím
2.1. Sử dụng lớp Scanner
Cú pháp khai báo:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);Các phương thức đọc dữ liệu:
| Phương thức | Kiểu trả về | Mô tả |
|---|---|---|
nextLine() | String | Đọc cả dòng (tới khi gặp Enter) |
next() | String | Đọc một từ (tới khi gặp khoảng trắng) |
nextInt() | int | Đọc một số nguyên |
nextDouble() | double | Đọc một số thực |
nextBoolean() | boolean | Đọc giá trị boolean |
nextByte() | byte | Đọc số byte |
nextShort() | short | Đọc số short |
nextLong() | long | Đọc số long |
nextFloat() | float | Đọc số float |
Ví dụ cơ bản:
import java.util.Scanner;
public class ScannerBasic {
public static void main(String[] args) {
// Tạo đối tượng Scanner
Scanner scanner = new Scanner(System.in);
// Đọc các kiểu dữ liệu khác nhau
System.out.print("Nhập tên: ");
String name = scanner.nextLine();
System.out.print("Nhập tuổi: ");
int age = scanner.nextInt();
System.out.print("Nhập chiều cao (m): ");
double height = scanner.nextDouble();
System.out.print("Bạn có thích Java không? (true/false): ");
boolean likesJava = scanner.nextBoolean();
// Hiển thị kết quả
System.out.printf("PTn=== THÔNG TIN ===");
System.out.printf("PTnTên: PTs", name);
System.out.printf("PTnTuổi: PTd", age);
System.out.printf("PTnChiều cao: PT.2f m", height);
System.out.printf("PTnThích Java: PTb", likesJava);
// Đóng Scanner
scanner.close();
}
}2.2. Vấn đề và giải pháp với Scanner
Vấn đề: Kết hợp nextLine() sau các phương thức khác
import java.util.Scanner;
public class ScannerProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập tuổi: ");
int age = scanner.nextInt();
// Vấn đề: nextInt() không đọc ký tự newline
System.out.print("Nhập tên: ");
String name = scanner.nextLine(); // Sẽ đọc rỗng!
System.out.println("Tuổi: " + age);
System.out.println("Tên: " + name); // Tên sẽ rỗng!
scanner.close();
}
}Giải pháp 1: Thêm nextLine() để xử lý newline
System.out.print("Nhập tuổi: ");
int age = scanner.nextInt();
scanner.nextLine(); // Đọc bỏ ký tự newline
System.out.print("Nhập tên: ");
String name = scanner.nextLine(); // Giờ sẽ hoạt động đúngGiải pháp 2: Luôn dùng nextLine() và chuyển đổi
System.out.print("Nhập tuổi: ");
String ageInput = scanner.nextLine();
int age = Integer.parseInt(ageInput);
System.out.print("Nhập chiều cao: ");
String heightInput = scanner.nextLine();
double height = Double.parseDouble(heightInput);Phần 3: Xử lý ngoại lệ (Exception Handling)
3.1. Cú pháp try-catch
Cú pháp cơ bản:
try {
// Code có thể gây lỗi
} catch (Loại_Ngoại_Lệ tên_biến) {
// Xử lý khi lỗi xảy ra
} finally {
// Luôn thực thi (dù có lỗi hay không)
}Các ngoại lệ thường gặp:
InputMismatchException: Nhập sai kiểu dữ liệuNumberFormatException: Chuyển đổi chuỗi sang số không thành côngArithmeticException: Lỗi tính toán (chia cho 0)IOException: Lỗi nhập/xuất
3.2. Ví dụ xử lý ngoại lệ
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Nhập số nguyên: ");
int number = scanner.nextInt();
System.out.print("Nhập số chia: ");
int divisor = scanner.nextInt();
int result = number / divisor;
System.out.println("Kết quả: " + result);
} catch (InputMismatchException e) {
System.out.println("Lỗi: Bạn phải nhập số nguyên!");
} catch (ArithmeticException e) {
System.out.println("Lỗi: Không thể chia cho 0!");
} catch (Exception e) {
System.out.println("Lỗi không xác định: " + e.getMessage());
} finally {
System.out.println("Chương trình kết thúc.");
scanner.close();
}
}
}Phần 4: Đọc và ghi file văn bản
4.1. Ghi file
Cú pháp1: Dùng lớp FileWriter:
FileWriter writer = new FileWriter("tên_file.txt");
writer.write("nội dung");
writer.close();Cú pháp 2: Dùng lớp PrintWriter:
PrintWriter writer = new PrintWriter("tên_file.txt");
writer.println("dòng 1");
writer.printf("Định dạng: %s", "giá trị");
writer.close();Ví dụ:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class WriteFileExample {
public static void main(String[] args) {
// Sử dụng FileWriter
try {
FileWriter writer = new FileWriter("data.txt");
writer.write("Dòng 1: Học Java\n");
writer.write("Dòng 2: Nhập xuất file\n");
writer.close();
System.out.println("Đã ghi file thành công!");
} catch (IOException e) {
System.out.println("Lỗi ghi file: " + e.getMessage());
}
// Sử dụng PrintWriter
try {
PrintWriter pw = new PrintWriter("output.txt");
pw.println("Tên: Nguyễn Văn A");
pw.printf("Tuổi: %d%n", 25);
pw.printf("Điểm: %.2f%n", 8.5);
pw.close();
} catch (IOException e) {
System.out.println("Lỗi: " + e.getMessage());
}
}
}4.2. Đọc file
Cú pháp 1: Dùng lớp BufferedReader:
BufferedReader reader = new BufferedReader(new FileReader("tên_file.txt"));
String line = reader.readLine();
reader.close();Cú pháp 2: Dùng Scanner đọc file:
Scanner fileScanner = new Scanner(new File("tên_file.txt"));
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
}
fileScanner.close();Ví dụ:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
// Sử dụng BufferedReader
System.out.println("=== Đọc bằng BufferedReader ===");
try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("Lỗi đọc file: " + e.getMessage());
}
// Sử dụng Scanner
System.out.println("\n=== Đọc bằng Scanner ===");
try {
Scanner fileScanner = new Scanner(new java.io.File("output.txt"));
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
fileScanner.close();
} catch (IOException e) {
System.out.println("Lỗi: " + e.getMessage());
}
}
}Phần 5: Bài tập thực hành
Bài tập 1: Tính tổng hai số
import java.util.Scanner;
public class SumTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Nhập số thứ nhất: ");
double num1 = scanner.nextDouble();
System.out.print("Nhập số thứ hai: ");
double num2 = scanner.nextDouble();
double sum = num1 + num2;
System.out.printf("Tổng của PT.2f và PT.2f là: PT.2f%n", num1, num2, sum);
scanner.close();
}
}Bài tập 2: Tính chỉ số BMI
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== TÍNH CHỈ SỐ BMI ===");
System.out.print("Nhập cân nặng (kg): ");
double weight = scanner.nextDouble();
System.out.print("Nhập chiều cao (m): ");
double height = scanner.nextDouble();
double bmi = weight / (height * height);
System.out.printf("PTn=== KẾT QUẢ ===PTn");
System.out.printf("Cân nặng: PT.1f kgPTn", weight);
System.out.printf("Chiều cao: PT.2f mPTn", height);
System.out.printf("Chỉ số BMI: PT.2fPTn", bmi);
if (bmi < 18.5) {
System.out.println("Phân loại: Thiếu cân");
} else if (bmi < 25) {
System.out.println("Phân loại: Bình thường");
} else if (bmi < 30) {
System.out.println("Phân loại: Thừa cân");
} else {
System.out.println("Phân loại: Béo phì");
}
scanner.close();
}
}Bài tập 3: Quản lý sinh viên với file
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class StudentFileManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== NHẬP THÔNG TIN SINH VIÊN ===");
System.out.print("Mã sinh viên: ");
String id = scanner.nextLine();
System.out.print("Họ tên: ");
String name = scanner.nextLine();
System.out.print("Điểm Toán: ");
double math = scanner.nextDouble();
System.out.print("Điểm Lý: ");
double physics = scanner.nextDouble();
System.out.print("Điểm Hóa: ");
double chemistry = scanner.nextDouble();
double average = (math + physics + chemistry) / 3;
// Ghi vào file
try {
FileWriter writer = new FileWriter("students.txt", true);
writer.write("=== SINH VIÊN ===\n");
writer.write("Mã SV: " + id + "\n");
writer.write("Họ tên: " + name + "\n");
writer.write(String.format("Điểm Toán: PT.1f\n", math));
writer.write(String.format("Điểm Lý: PT.1f\n", physics));
writer.write(String.format("Điểm Hóa: PT.1f\n", chemistry));
writer.write(String.format("Điểm TB: PT.2f\n", average));
writer.write("=================\n\n");
writer.close();
System.out.println("\nĐã lưu thông tin vào file students.txt");
} catch (IOException e) {
System.out.println("Lỗi ghi file: " + e.getMessage());
}
scanner.close();
}
}Bài tập về nhà:
- Viết chương trình tính tiền điện với bậc thang
- Viết chương trình quy đổi tiền tệ (USD – VND)
- Tạo chương trình nhật ký cá nhân (ghi và đọc từ file)
