问题是我无法使用next()读取变量输入,因为当我尝试用.split(" ")分割每个空格时,数组只获取我输入的前两个单词,所以我不得不使用keyboard.nextLine(),这样分割过程就可以正常工作,并且我可以在数组中获得所有单词,但问题是如果我使用nextLine(),那么我必须创建另一个keyboard对象来读取第一个变量(答案),这是我能让它工作的唯一方法,以下是代码:
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++;
}
}
}
}
谢谢 :)