有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

结果不正确的java数据输入问题?

查看代码。 当我启动程序时,它不允许我将scanner类输入插入交换机,为什么

Scanner in = new Scanner(System.in);

System.out.println("select:");
int select = in.nextInt();

switch (select) {
case 1:
System.out.println("first name:");
String n = in.nextLine();
System.out.println("surname:");
String s = in.nextLine();

System.out.println(n + s);
break;
}

输出:

选择: 1. 名字: 姓:


共 (2) 个答案

  1. # 1 楼答案

    nextLine方法被忽略,因为nextLine方法中保留了换行符。有两种方法可以解决此问题

    解决方案1:

    Scanner in = new Scanner(System.in);
    System.out.println("select:");
    int select = in.nextInt();
    
    in.nextLine();
    

    解决方案2:

    Scanner in = new Scanner(System.in);
    System.out.println("select:");
    int select = Integer.parseInt(in.nextLine());
    
  2. # 2 楼答案

    BufferedReaderInputStreamReader替换Scanner可以修复它,请尝试:

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    System.out.println("select:");
    int select = Integer.parseInt(input.readLine());
    
    switch (select) {
        case 1:
            System.out.println("first name:");
            String n = Integer.parseInt(input.readLine());
            System.out.println("surname:");
            String s = Integer.parseInt(input.readLine());
    
            System.out.println(n + s);
        break;
    }