use*_*331 1 java string split next
问题是当我尝试拆分(.split"")每个空格时,我无法读取带有next()的变量输入,然后数组只得到我输入的前两个单词,所以我不得不使用keyboard.nextLine()和分裂过程的工作方式应该工作,我得到数组中的所有单词,但问题是,如果我使用nextLine()然后我必须创建另一个键盘对象来读取第一个变量(答案),这是唯一的方法我可以让它在这里工作是代码
Scanner keyboard=new Scanner(System.in);
Scanner keyboard2=new Scanner(System.in);//just to make answer word
int answer=keyboard.nextInt();//if I don't use the keyboard2 here then the program will not work as it should work, but if I use next() instead of nextLine down there this will not be a problem but then the splitting part is a problem(this variable counts number of lines the program will have).
int current=1;
int left=0,right=0,forward=0,back=0;
for(int count=0;count<answer;count++,current++)
{
String input=keyboard.nextLine();
String array[]=input.split(" ");
for (int counter=0;counter<array.length;counter++)
{
if (array[counter].equalsIgnoreCase("left"))
{
left++;
}
else if (array[counter].equalsIgnoreCase("right"))
{
right++;
}
else if (array[counter].equalsIgnoreCase("forward"))
{
forward++;
}
else if (array[counter].equalsIgnoreCase("back"))
{
back++;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
Eng*_*uad 11
放在keyboard.nextLine()这一行之后:
int answer=keyboard.nextInt();
Run Code Online (Sandbox Code Playgroud)
这是当你使用通常发生在一个共同的问题nextLine()之后方法nextInt()的方法Scanner类.
实际发生的情况是,当用户输入整数时int answer = keyboard.nextInt();,扫描仪将仅采用数字并保留换行符\n.所以你需要通过调用keyboard.nextLine();只是为了丢弃新行字符然后你可以String input = keyboard.nextLine();毫无问题地调用.