使用Scanner類(lèi)進(jìn)行輸入操作需要進(jìn)行以下步驟:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
next()
方法獲取輸入的字符串:String inputString = scanner.next();
nextInt()
方法獲取輸入的整數(shù):int inputInt = scanner.nextInt();
nextDouble()
方法獲取輸入的浮點(diǎn)數(shù):double inputDouble = scanner.nextDouble();
nextBoolean()
方法獲取輸入的布爾值:boolean inputBoolean = scanner.nextBoolean();
scanner.close();
完整示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("請(qǐng)輸入一個(gè)字符串:");
String inputString = scanner.next();
System.out.println("輸入的字符串為:" + inputString);
System.out.print("請(qǐng)輸入一個(gè)整數(shù):");
int inputInt = scanner.nextInt();
System.out.println("輸入的整數(shù)為:" + inputInt);
System.out.print("請(qǐng)輸入一個(gè)浮點(diǎn)數(shù):");
double inputDouble = scanner.nextDouble();
System.out.println("輸入的浮點(diǎn)數(shù)為:" + inputDouble);
System.out.print("請(qǐng)輸入一個(gè)布爾值(true/false):");
boolean inputBoolean = scanner.nextBoolean();
System.out.println("輸入的布爾值為:" + inputBoolean);
scanner.close();
}
}
注意事項(xiàng):
nextInt()
、nextDouble()
等方法獲取輸入后,如果還需要獲取字符串輸入,需要使用nextLine()
方法來(lái)消費(fèi)掉之前輸入的回車(chē)符??梢栽谡{(diào)用nextLine()
方法之前先調(diào)用scanner.nextLine()
進(jìn)行清空緩沖區(qū)。int inputInt = scanner.nextInt();
scanner.nextLine(); // 清空緩沖區(qū)
String inputString = scanner.nextLine();