简体   繁体   中英

How can I read an empty line in Java?

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.

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM