读取字符串 next() 和 nextLine() Java [英] Reading Strings next() and nextLine() Java
问题描述
问题是当我尝试拆分 (.split" ") 每个空格时,我无法使用 next() 读取变量输入,然后数组只获取我输入的前两个单词,因此我不得不使用 keyboard.nextLine() 并且拆分过程按照它应该的方式工作,我得到了数组中的所有单词,但问题是如果我使用 nextLine() 那么我必须创建另一个键盘对象来读取第一个变量(答案),那就是我可以让它在这里工作的唯一方法是代码
Scanner keyboard=new Scanner(System.in);Scanner keyboard2=new Scanner(System.in);//只是为了让回答词int answer=keyboard.nextInt();//如果我在这里不使用keyboard2,那么程序将无法正常工作,但是如果我在那里使用next()而不是nextLine,这将不是问题,但是那么拆分部分是一个问题(这个变量计算程序将拥有的行数).int电流=1;int left=0,right=0,forward=0,back=0;for(int count=0;count<answer;count++,current++){字符串输入=keyboard.nextLine();字符串数组[]=input.split(" ");for (int counter=0;counter
谢谢:)
将 keyboard.nextLine()
放在这一行之后:
int answer=keyboard.nextInt();
这是一个常见的问题,当你在Scanner
类的nextInt()
方法之后使用nextLine()
方法时通常会发生.>
实际发生的情况是,当用户在 int answer = keyboard.nextInt();
处输入一个整数时,扫描器将只取数字并留下换行符
.所以你需要通过调用 keyboard.nextLine();
来做一个技巧,只是为了丢弃那个换行符,然后你可以调用 String input = keyboard.nextLine();
没有任何问题.
The problem is I cant read the variable input with next() cause when I try to split (.split" ") every whitespace then the array just get the first two words I type so I had to use keyboard.nextLine() and the splitting process works the way it should work and I get all the words in the array but the problem is that If I use nextLine() then I have to create another keyboard object to read the first variable (answer) and that is the only way I can make it work here is the code
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++;
}
}
}
}
Thanks :)
Put keyboard.nextLine()
after this line:
int answer=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine()
method after nextInt()
method of Scanner
class.
What actually happens is that when the user enters an integer at int answer = keyboard.nextInt();
, the scanner will take the digits only and leave the new-line character
. So you need to do a trick by calling keyboard.nextLine();
just to discard that new-line character and then you can call String input = keyboard.nextLine();
without any problem.
这篇关于读取字符串 next() 和 nextLine() Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!