简单的Java扫描器代码不起作用 [英] Simple Java Scanner code not working

查看:109
本文介绍了简单的Java扫描器代码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在编写的用于编写简单游戏的一些基本代码的框架:

Here is the skeleton of some basic code I am writing to make a simple game:

    Scanner in = new Scanner(System.in);

    String name;
    String playing;
    int age;

    do {

        System.out.println("Enter your name");
        name = in.nextLine();

        System.out.println("Enter your age");
        age = in.nextInt();

        System.out.println("Play again?");
        playing = in.nextLine();

    } while (true);

该代码无法正常工作,例如,这是该代码的预期功能:

The code does not work as expected, for example, here is the expected functioning of the code:

Enter your name
John
Enter your age
20
Play again?
Yes
Enter your name
Bill
...

但是,读取再次播放行存在问题,这是实际输出:

However, there is an issue with reading the Play again line, this is the actual output:

Enter your name
John
Enter your age
20
Play again?
Enter your name

您可以看到在再次播放?"之前再次显示输入您的姓名".能够接受输入.调试播放变量时,将其设置为",因此我看不到任何输入,也无法弄清楚消耗了什么. 任何帮助将不胜感激,谢谢!

As you can see "Enter your name" is being displayed again before "Play again?" is able to accept input. When debugging the playing variable is set to "", so there is no input that I can see and I cannot figure out what is being consumed. Any help would be appreciated, thanks!

推荐答案

nextInt()不会占用行尾,即使int是其中唯一的东西.

nextInt() doesn't consume the end-of-line, even if the int is the only thing in there.

在读取int之后再添加一个nextLine(),或者完全丢弃其值,或者如果要防止其他人输入除int之外的其他内容,请检查其是否为空.

Add another nextLine() after reading the int, and either discard its value completely, or check that it is empty if you want to prevent people from entering anything but an int.

这篇关于简单的Java扫描器代码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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