0

I want to be able to read an empty line if the user presses enter, but at the same time I want to be able to read a line with content if he inserts any.

System.out.println("Name> ");
String nome = sc.nextLine();
System.out.println("--" + nome + "--");
System.out.println("Id> ");
String id = sc.nextLine();
System.out.println(" ")

The problem is that everytime the user inserts any content, I only receive an empty String.

Pedro
  • 11
  • 1
  • 1
    What do you do with `sc` before `sc.nextLine()` - do you have a call like `sc.next()` or `sc.nextDouble()` ? – Joni Aug 14 '20 at 13:30
  • From that snippet, you're not printing `id` out, just an empty space. – Rogue Aug 15 '20 at 06:17

2 Answers2

0

I think sc is a scanner object so I have completed your code like this.

Scanner sc = new Scanner(new InputStreamReader(System.in));
    System.out.println("Name> ");
    String nome = sc.nextLine();
    System.out.println("--" + nome + "--");
    System.out.println("Id> ");
    String id = sc.nextLine();
    System.out.println(" ");

this works fine

this is the output for a line with content 
Name> 
wahidullah
--wahidullah--
Id> 
200

and

this is the ouput for an empty line
Name> 

----
Id> 

hopes this works for you

0

I agree with @Wahidullah Shah.

But, I believe the problem in your case is caused by using nextLine() right after nextInt(),next(),etc. I make this assumption based on the fact that you have provided only a small piece of your code.

The problem is, nextInt() does not consume return character. When nextLine() is called right after that, it simply consumes the return character, thus giving you empty string.

Research Links:

halfer
  • 18,701
  • 13
  • 79
  • 158