使用 java.util.Scanner() 读取多个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20190523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read multiple word strings with java.util.Scanner()
提问by Dave Carruthers
I want to read a full name in from the console using java.util.Scanner() and assign that value to a string.
我想使用 java.util.Scanner() 从控制台读取全名并将该值分配给一个字符串。
for example;
例如;
Type "John Smith" in console. Hit return and String s = "John Smith";
在控制台中输入“John Smith”。点击返回和 String s = "John Smith";
I tried writing a readString method to do this but its getting loop locked. Does anyone know a soloution?.
我尝试编写一个 readString 方法来执行此操作,但它正在锁定循环。有谁知道解决办法?
part of my code.
我的代码的一部分。
System.out.println("Name: ");
String name = readString();
and my broken method.
和我的坏方法。
private String readString()
{
String s ="";
while(scanner.hasNext())
s += scanner.next();
return s;
}
采纳答案by Prabhakaran Ramaswamy
Use nextLine()method instead of next()
使用nextLine()方法代替next()
Do like this
这样做
private String readString()
{
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
回答by Ruchira Gayan Ranaweera
This may help you
这可能会帮助你
public static void main(String[] args) {
System.out.println("Name: "+getInput());
}
private static String getInput() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}