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 input = scanner.nextLine();
System.out.println("你輸入的是:" + input);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個整數:");
int number = scanner.nextInt();
System.out.println("你輸入的整數是:" + number);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個雙精度浮點數:");
double decimal = scanner.nextDouble();
System.out.println("你輸入的雙精度浮點數是:" + decimal);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一個單精度浮點數:");
float singleDecimal = scanner.nextFloat();
System.out.println("你輸入的單精度浮點數是:" + singleDecimal);
}
}
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 flag = scanner.nextBoolean();
System.out.println("你輸入的布爾值是:" + flag);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一行文本:");
scanner.nextLine(); // 消耗換行符
System.out.println("請輸入一個整數:");
int number = scanner.nextInt();
System.out.println("你輸入的整數是:" + number);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入一行文本:");
scanner.nextLine(); // 消耗換行符
if (scanner.hasNextInt()) {
System.out.println("請輸入一個整數:");
int number = scanner.nextInt();
System.out.println("你輸入的整數是:" + number);
} else {
System.out.println("沒有下一個整數");
}
}
}