我试图了解执行此命令后为什么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);
}

最佳答案

nextLine()在读取字符之前先读取换行符。添加额外的nextLine()以读取该新行。

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

10-07 12:09