Java的Scanner類可以很容易地讀取不同類型的數據。以下是一些常見數據類型的讀取方法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
String inputString = scanner.nextLine();
System.out.println("你輸入的字符串是:" + inputString);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個整數:");
int inputInt = scanner.nextInt();
System.out.println("你輸入的整數是:" + inputInt);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個浮點數:");
float inputFloat = scanner.nextFloat();
System.out.println("你輸入的浮點數是:" + inputFloat);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個雙精度浮點數:");
double inputDouble = scanner.nextDouble();
System.out.println("你輸入的雙精度浮點數是:" + inputDouble);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個布爾值(true/false):");
boolean inputBoolean = scanner.nextBoolean();
System.out.println("你輸入的布爾值是:" + inputBoolean);
}
}
注意:在讀取數據之前,需要確保輸入流中有數據。否則,nextInt()
、nextFloat()
等方法會拋出NoSuchElementException
異常。如果需要處理這種異常,可以使用try-catch
語句。