读取字符串next()和nextLine()Java
问题是我无法使用next()读取变量输入,因为当我尝试拆分(.split“”)每个空格时,数组只会得到我键入的前两个单词,因此我必须使用keyboard.nextLine()和拆分过程按其应该的方式工作,我会得到数组中的所有单词,但问题是如果我使用nextLine()的话然后我必须创建另一个键盘对象来读取第一个变量(answer),这是我唯一能让它在这里工作的方法就是代码读取字符串next()和nextLine()Java,java,string,split,next,Java,String,Split,Next,问题是我无法使用next()读取变量输入,因为当我尝试拆分(.split“”)每个空格时,数组只会得到我键入的前两个单词,因此我必须使用keyboard.nextLine()和拆分过程按其应该的方式工作,我会得到数组中的所有单词,但问题是如果我使用nextLine()的话然后我必须创建另一个键盘对象来读取第一个变量(answer),这是我唯一能让它在这里工作的方法就是代码 Scanner keyboard=new Scanner(System.in); Scanner keybo
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++;
}
}
}
}
扫描仪键盘=新扫描仪(System.in);
扫描仪键盘2=新扫描仪(System.in)//只是为了回答这个问题
int answer=keyboard.nextInt()//如果我在这里不使用键盘2,那么程序将无法正常工作,但是如果我在下面使用next()而不是nextLine,这将不会是一个问题,但是拆分部分是一个问题(此变量计算程序将具有的行数)。
int电流=1;
int left=0,right=0,forward=0,back=0;
对于(int count=0;countPutkeyboard.nextLine()
int answer=keyboard.nextInt();
这是一个常见问题,通常在Scanner
类的nextLine()方法之后使用nextLine()
方法时发生
实际情况是,当用户在int answer=keyboard.nextLine();
处输入一个整数时,扫描器将只取数字并保留新行字符\n
。因此,您需要通过调用keyboard.nextLine()来完成一个技巧;
只需丢弃新行字符,然后您就可以毫无问题地调用String input=keyboard.nextLine();
。将keyboard.nextLine()
放在此行之后:
int answer=keyboard.nextInt();
这是一个常见问题,通常在Scanner
类的nextLine()方法之后使用nextLine()
方法时发生
实际情况是,当用户在int answer=keyboard.nextLine();
处输入一个整数时,扫描器将只取数字并保留新行字符\n
。因此,您需要通过调用keyboard.nextLine()来完成一个技巧;
只需丢弃新行字符,然后就可以调用String input=keyboard.nextLine()
没有任何问题。请您编辑您的问题以包含标点符号。很难理解您的问题是什么。请您编辑您的问题以包含标点符号。很难理解您的问题是什么。