You are on page 1of 4

Bài tập I/O và File

Bài 1: Bài toán hiển thị popup

Kiến thức cần tập trung:

- Sử dụng JOptionPane để hiển thị thông báo


- Ôn lại câu lệnh IF

import javax.swing.JOptionPane;

public class WelcomeBox {

public static void main(String[] args) {

double ketqua = Math.random() ;

ketqua *= 100;

if(ketqua >=50){

JOptionPane.showMessageDialog(null, "You win! Welcome to Java!",


"CNTT K23", JOptionPane.INFORMATION_MESSAGE);

}else {

JOptionPane.showMessageDialog(null, "You you have lost!", "CNTT K23",


JOptionPane.INFORMATION_MESSAGE);

Bài 2: Nhập dữ liệu với popup

Kiến thức cần tập trung:

- Nhập dữ liệu với JoptionPane


- Chuyển dữ liệu từ kiểu String sang kiểu số
- Ôn lại lệnh while, for

import javax.swing.JOptionPane;
public class Ex2WithWhile {

public static void main(String[] args) {

boolean youLost = true;

while (youLost) {

String input= JOptionPane.showInputDialog(null, "Moi ban choi loto",


"CNTT K23", JOptionPane.QUESTION_MESSAGE);

long inputNumber = Integer.parseInt(input);

for(int i =0; i<25; i++){

double ketquaDouble = Math.random()*100;

long ketquaInt = Math.round(ketquaDouble) ;

if(ketquaInt == inputNumber){

youLost = false; // you win

break;

}//end of for

if(!youLost){

JOptionPane.showMessageDialog(null, "You win! Welcome to


Java!", "CNTT K23", JOptionPane.INFORMATION_MESSAGE);

}else {

JOptionPane.showMessageDialog(null, "You you have lost!",


"CNTT K23", JOptionPane.INFORMATION_MESSAGE);

//System.out.println("ban thua roi");

}//end of while

}
Bài 3: Làm việc với f il e văn b ản (txt): Ghi nội du n g ra f il e văn bản.

Kiến thức cần tập trung:

- Đối tượng DataOutputStream


- Đối tượng File
- Đối tượng DataOutputStream
- Ôn lại try-catch

DataOutputStream dos;
public boolean writeToFile(String fileName, String dataLine,
boolean isAppendMode, boolean isNewLine) {
if (isNewLine) {
dataLine = "\n" + dataLine;
}
try {
File outFile = new File(fileName);
if (isAppendMode) {
dos = new DataOutputStream(new
FileOutputStream(fileName, true));
} else {
dos = new DataOutputStream(new
FileOutputStream(outFile));
}

dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);

Bài 4: Làm việc với f il e văn b ản : Đọc f il e văn bản

Kiến thức cần tập trung:

- Đối tượng BufferedReader


- Đối tượng BufferedReader
- Đối tượng InputStreamReader

public String readFromFile(String fileName) {


String DataLine = "";
try {
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(new
InputStreamReader(

4
new
FileInputStream(inFile))); DataLine =
br.readLine();
br.close();
} catch (FileNotFoundException ex) {
return (null);
} catch (IOException
ex) {
return (null);
}
return (DataLine);
}

You might also like