无法从Scanner类中的nextLine()分配字符串值

时间:2015-08-06 12:15:31

标签: java java.util.scanner

我正在尝试理解为什么inputString在执行此

后仍然为空
    public static void main(String[] args) {
    // write your code here

    int inputInt = 0;
    double inputDouble = 0.0;
    String inputString = null;

    Scanner scanner3 = new Scanner(System.in);

    if (scanner3.hasNext()) {
        inputInt = scanner3.nextInt();
    }


    if (scanner3.hasNext()) {
        inputDouble = scanner3.nextDouble();
    }

    if (scanner3.hasNext()) {
        inputString = scanner3.nextLine();
    } else {
        throw new RuntimeException("No entries left");
    }

    System.out.println("String: " + inputString);
    System.out.println("Double: " + inputDouble);
    System.out.println("Int: " + inputInt);
}

1 个答案:

答案 0 :(得分:1)

nextLine()在阅读你的角色之前阅读换行符号。添加额外的nextLine()以阅读该新行。

 if (scanner3.hasNext()) {
        scanner3.nextLine();
        inputString = scanner3.nextLine();
 }