英文:
How can I read an empty line in Java?
问题
我希望能够在用户按下回车键时读取空行,但与此同时,如果用户输入任何内容,我也希望能够读取到有内容的行。
System.out.println("请输入姓名:");
String name = sc.nextLine();
System.out.println("--" + name + "--");
System.out.println("请输入ID:");
String id = sc.nextLine();
System.out.println(" ");
问题是,每次用户输入任何内容时,我只会收到一个空字符串。
英文:
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.
答案1
得分: 0
Sure, here's the translated code:
我认为sc是一个扫描器对象,所以我已经根据您的代码完成了如下编写:
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(" ");
这个可以正常工作
这是带有内容的一行的输出
Name>
wahidullah
--wahidullah--
Id>
200
和
这是空行的输出
Name>
----
Id>
希望这对您有用
Please note that I've only provided the translated code portion as requested. Let me know if you need any further assistance!
英文:
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
答案2
得分: 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 the return character. When nextLine() is called right after that, it simply consumes the return character, thus giving you an empty string.
Research Links:
英文:
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:
专注分享java语言的经验与见解,让所有开发者获益!
评论