Java扫描器不期望下一个输入,忽略nextLine() [英] Java Scanner does not expect next input, ignores nextLine()

查看:61
本文介绍了Java扫描器不期望下一个输入,忽略nextLine()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有真正了解扫描仪的行为.我想先输入一个int,然后在while循环中输入下一行输入.但是在第一个输入之后,我得到一个ArrayOutOfBoundsException,如下所示.它只是忽略了我要输入下一行的内容.唯一的解决方案是当我输入int并在一行中用空格分隔新行时,但这不是我想要的,因为在这一点上,用户不知道在第一个int之后要输入什么.

I don't really get the behaviour of the Scanner. I want to input a single int first and in the while-loop, as you can see, next line inputs. But after the first input I get an ArrayOutOfBoundsException as you can see below. It just ignores that I want to input next lines. The only solution is when I input the int and the new line separated with a space in one line, but that isn't what I want, because at this point, the user doesn't know, what to input after the first int.

Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt() - 1;
        logic.setGameField(games.get(i).getGameField());

//      scanner.reset(); //what does that do?

        view.displayField(logic.getCompleteGameField(), logic.getGameSize(), logic.getCompleteGameSize());

        double time = System.currentTimeMillis();


        while (!logic.gameIsFinished()) {
            System.out.println("Spalte Reihe Zeichen: X/*");

            String s = scanner.nextLine();

            char[] tmp = s.toCharArray(); 

            //just for testing
            System.out.println(s.length()); //outputs: 0
            System.out.println(tmp.length); //outputs: 0
            for (int j = 0; j < tmp.length; j++) {
                System.out.print(tmp[j] + " " + j);     
            }
            System.out.println();

            logic.setSingleField(tmp[1] - CHAR_TO_INT_OFFSET_ROW, tmp[0] - CHAR_TO_INT_OFFSET_COLUMN, tmp[2]); //throws as expected ArrayIndexOutOfBoundsException

推荐答案

这是因为Scanner.nextInt()不会将您带到下一行.此时,您仍处于当前输入行中.您可以做的是在Scanner.nextInt()之后调用附加的Scanner.nextLine():

This is because Scanner.nextInt() doesn't bring you to the next line. At this point, you are still in current line of input. What you can do is call an additional Scanner.nextLine() after Scanner.nextInt():

int i = scanner.nextInt() - 1;
scanner.nextLine();
logic.setGameField(games.get(i).getGameField());

这篇关于Java扫描器不期望下一个输入,忽略nextLine()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆