阅读字符串next()和nextLine()Java
问题描述:
问题是我无法用next()读取变量输入,当我尝试拆分(.split“”)每个空白,然后数组只是得到前两个单词I键入所以我不得不使用keyboard.nextLine()和分裂过程的工作方式,它应该工作,我得到的数组中的所有单词,但问题是,如果我使用nextLine(),那么我必须创建另一个键盘对象读第一个变量(答案),这是我可以在这里工作的唯一方法是代码阅读字符串next()和nextLine()Java
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();
处输入一个整数时,扫描器将只取数字并留下换行符\n
。所以你需要通过调用keyboard.nextLine();
来唬住这个新行字符,然后你可以打电话String input = keyboard.nextLine();
没有任何问题。
请问您可以编辑您的问题以包含标点符号。真的很难理解你的问题是什么。 – 2012-01-15 21:12:47