读取字符串next()和nextLine()Java

问题是当我尝试拆分(.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++; } } } } 

谢谢 :)

在此行之后放置keyboard.nextLine()

 int answer=keyboard.nextInt(); 

这是在Scanner类的nextInt()方法之后使用nextLine()方法时经常发生的常见问题。

实际发生的是当用户在int answer = keyboard.nextInt();时输入一个整数时int answer = keyboard.nextInt(); ,扫描仪将仅采用数字并保留换行符\n 。 所以你需要通过调用keyboard.nextLine();来做一个技巧keyboard.nextLine(); 只是为了丢弃该换行符,然后你可以调用String input = keyboard.nextLine(); 没有任何问题。