使用Scanner类进行输入操作需要进行以下步骤:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
next()
方法获取输入的字符串:String inputString = scanner.next();
nextInt()
方法获取输入的整数:int inputInt = scanner.nextInt();
nextDouble()
方法获取输入的浮点数: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("请输入一个字符串:");
String inputString = scanner.next();
System.out.println("输入的字符串为:" + inputString);
System.out.print("请输入一个整数:");
int inputInt = scanner.nextInt();
System.out.println("输入的整数为:" + inputInt);
System.out.print("请输入一个浮点数:");
double inputDouble = scanner.nextDouble();
System.out.println("输入的浮点数为:" + inputDouble);
System.out.print("请输入一个布尔值(true/false):");
boolean inputBoolean = scanner.nextBoolean();
System.out.println("输入的布尔值为:" + inputBoolean);
scanner.close();
}
}
注意事项:
nextInt()
、nextDouble()
等方法获取输入后,如果还需要获取字符串输入,需要使用nextLine()
方法来消费掉之前输入的回车符。可以在调用nextLine()
方法之前先调用scanner.nextLine()
进行清空缓冲区。int inputInt = scanner.nextInt();
scanner.nextLine(); // 清空缓冲区
String inputString = scanner.nextLine();