0

I am trying to read a String and output it to the terminal, as well as a few primitives, but it does not seem to work. The code is below:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s = scan.nextLine();

        scan.close();
        
        System.out.println("String: " + s + "\n");
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);

    }
}

I have tried to find other ways to parse the string in the Scanner class, but none of them seemed to work. What I except is for the String to be properly read and outputed to the terminal, along with the few other values.

Thanks in advance.

1 Answers1

0

The problem is that when you press enter (when you digit the number) you are inserting a \n character inside the buffer, so when you will call nextLine() you will read the \n (because nextLine reads the input until the \n) and you will not be able to write anything because the function returns when found the \n. You can clean it calling scanner.nextLine() one more time

int i = scan.nextInt();
double d = scan.nextDouble();
// Remove \n from buffer
scan.nextLine();
String s = scan.nextLine();
mamo
  • 266
  • 1
  • 3
  • 10
  • 1
    Or to be safer we can call `scan.skip("\\R?")` to skip line separator, if it exists. This way we don't risk that additional `nextLine()` will consume potential data left in same line, like `2.34 foo bar` when after `nextDouble` which would read `2.34` the the `nextLine()` *should* read `" foo bar"`. This would be impossible with extra `nextLine` before `String s = scan.nextLine();`. – Pshemo Jan 23 '23 at 20:53