0

I'm trying to understand why inputString is still empty after executing this

    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);
}
doubleH90
  • 133
  • 4
  • 16

1 Answers1

1

nextLine() read new line character before read your character. Add a extra nextLine() to read that new line.

 if (scanner3.hasNext()) {
        scanner3.nextLine();
        inputString = scanner3.nextLine();
 }
Buru
  • 8,018
  • 7
  • 47
  • 77