Java do-while循环简单问题 [英] Java do-while loop simple issue

查看:100
本文介绍了Java do-while循环简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有几年没有编码了,并且一直在编写简单的Java程序来重新熟悉基本原理。但是,我在执行do-while循环时遇到了麻烦。我想我不太清楚do-while循环是如何工作的,但是我想要的是从System.in中将用户输入作为int进行收集,如果他们输入其他数据形式,则继续要求输入有效的int输入。我所拥有的是:

I haven't coded in a few years and have been writing simple Java programs to re-familiarize myself with basic principles. However, I'm having trouble getting my do-while loop to act how I want it to. I guess I'm not understanding exactly how do-while loops work, but what I want is to gather user input from System.in as an int, and continue to ask for a valid int input if they enter some other data form. What I have is:

do {
    System.out.print("Input: ");

    userOption = userInput.nextInt();

} while (!userInput.hasNextInt());

System.out.println("You chose to: " + menuItems.get((userOption - 1)));

这不起作用有两个原因。首先,如果我输入非整数值,则会立即崩溃,并抛出输入不匹配异常。其次,如果我输入有效的int,则总是必须输入两次。 IE,控制台将询问输入:,我将输入 2,控制台将前进到下一行并等待另一输入(但不打印任何内容),然后在我输入第二个整数时输出您选择[...]。

This doesn't work for two reasons. First, if I enter a non-int value, it immediately crashes throwing an input mismatch exception. Second, if I do enter a valid int, I always have to enter it twice. I.E., the console will ask for "Input: ", I'll enter say "2", the console will advance to the next line and wait for another input (but without printing anything), and then when I enter a second int it outputs the "You chose to [...]".

我尝试了十几种不同的变体,这些变体会变得越来越复杂,而do-while内的循环会在if-else内部,但是我确定我已经使事情复杂化了,并且错过了一个简单的概念。

I have tried over a dozen different variations that just keep getting more complex, while loops inside do-while, inside if-else, but I'm sure I'm over complicating matters and am missing a simple concept. Any help is very much appreciated!

推荐答案

这里是一个独立的示例:

Here is a stand alone example:

import java.util.*;

public class Foo {
  public static void main(String args[]){
        int userOption;
        Scanner userInput = new Scanner(System.in);

        System.out.print("Input: "); 
        while(!userInput.hasNextInt()){
            userInput.next();
            System.out.print("Error: Please enter an integer\nInput: "); 
        } 
        userOption = userInput.nextInt();

        System.out.println("You chose to: " +userOption);
    }
}

我们希望在第一时间就输入内容找不到整数,我们将显示错误消息并丢弃用户输入的任何内容( userInput.next(),另请参见: https://stackoverflow.com/a/15973109/1063730 )。

We ask for input the first time and while we can't find an integer we're going to display an error message and discard whatever was entered by user (userInput.next(), see also: https://stackoverflow.com/a/15973109/1063730).

这篇关于Java do-while循环简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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