问题描述
如果我无法解释这个问题,我很抱歉。当我接受用户输入时,它只打印字符串的第一个单词。 帮助我了解我缺少什么,或者当我接受用户输入时为什么它不起作用。
当我传递输入“This is Mango”时,它只打印
This
。
相反,我想将其打印为 This
is
Mango
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
String str= in.next();
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
如果我给出一个硬编码的字符串,它可以将它保存在数组中。
String str = "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.println(words[i]+" ");
当我运行上面的代码时,它打印为
This
is
a
sample
sentence
解决方法
更改这一行:
String str = in.next();
为此:
String str = in.nextLine();
这样,您的 Scanner 对象将读取整行输入。
如果您只使用 next()
,它只会读取输入,直到遇到空格。同时, nextLine()
读取整行(直到您在提供输入时转义到下一行)。另请注意,如果您想读取其他数据类型,则需要使用相应的函数。例如,要读取一个整数,您应该使用 nextInt()
。
希望这会有所帮助!