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

3
问题是我无法使用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++;
            }
        }

   }
}

谢谢 :)


1
请问您能否编辑一下您的问题,加上标点符号。这样我们才能更好地理解您的问题。谢谢。 - W.K.S
2个回答

13

在这行代码后面加上 keyboard.nextLine()

int answer=keyboard.nextInt();

这是一个常见的问题,通常在您使用 Scanner 类的 nextInt() 方法之后使用 nextLine() 方法时会发生。

实际上,当用户在 int answer = keyboard.nextInt(); 处输入整数时,扫描器仅获取数字并留下换行符 \n。因此,您需要通过调用 keyboard.nextLine(); 来丢弃该换行符,然后您就可以调用 String input = keyboard.nextLine(); 而没有任何问题。


0

我的第一个建议是将整行按空格分割后添加到 String 数组中。
然后,利用 Integer.parseInt 方法将 answer 赋值为数组的第 0 个索引。

这是您的代码,已经重构过了。

Scanner keyboard = new Scanner(System.in);
String[] strings = keyboard.nextLine().split(" ");
int answer = Integer.parseInt(strings[0]);
int left = 0, right = 0, forward = 0, back = 0;
for (int countA = 0; countA < answer; countA++) {
    for (String string : strings) {
        switch (string.toLowerCase()) {
            case "left" -> left++;
            case "right" -> right++;
            case "forward" -> forward++;
            case "back" -> back++;
        }
    }
}

输入

10 left right back left

输出

answer = 10
strings = [10, left, right, back, left]
left = 20
right = 10
forward = 0
back = 10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接