import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 讀取字符串
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.println("You entered: " + str);
// 讀取整數
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
scanner.close();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// 讀取字符串
System.out.print("Enter a string: ");
String str = reader.readLine();
System.out.println("You entered: " + str);
// 讀取整數
System.out.print("Enter an integer: ");
int num = Integer.parseInt(reader.readLine());
System.out.println("You entered: " + num);
reader.close();
}
}
注意:使用BufferedReader類讀取整數時,需要將讀取的字符串轉換為整數類型。