首页 > 解决方案 > 扫描仪无法从控制台读取 int 后的字符串?

问题描述

我正在使用 Scanner 对象从控制台读取值。如果我连续读取 2 个字符串,一切正常:

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the first string");
    String first = sc.nextLine();

    System.out.println("Enter the second string");
    String second = sc.next();

但是,如果我尝试先读取 Integer,然后再读取这两个字符串:

 Scanner sc = new Scanner(System.in);
    System.out.println("Enter num");
    int a = sc.nextInt();
    System.out.println("Enter the first string");
    String first = sc.nextLine();

    System.out.println("Enter the second string");
    String second = sc.nextLine();

    System.out.println("First '" + first + "'; second '" + second + "'");

然后行 String first = sc.nextLine(); 没有写在变量中,以某种方式跳过=/

检查控制台输出:

Enter num
123                   //(it is input)
Enter the first string
Enter the second string //(This and previous line appear together)
Str                   //(Only one line appears for input)

First ''; second 'Str'

在调试中,我提供输入第一个字符串,我输入它,然后在下一步调试器将此变量显示为空字符串。

它应该像这样工作吗?

标签: javastringconsoleintjava.util.scanner

解决方案


推荐阅读