【问题标题】:Using || in while loop makes it take too many input values使用 ||在 while 循环中,它需要太多的输入值
【发布时间】:2017-11-26 19:36:35
【问题描述】:
public class MetricConversion {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    String masses = "null";
    String volumes = "null";
    String temps = "null";
    String lengths = "null";
    int answer1 = 0;

    String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"};
    System.out.println("What would you like to convert?");
    for(int i = 0;i<options.length;i++)
        System.out.println(options[i]);

    while(!input.hasNextInt() || input.nextInt() > options.length)
    {
        String garbage = input.nextLine();
        System.out.println("That input is not valid, try again");
    }
    answer1 = input.nextInt();  
    input.nextLine();

我遇到的问题是

    while(!input.hasNextInt() || input.nextInt() > options.length)

为了使

采用 2 个有效输入而不是 1 个
    answer1 = input.nextInt();

例如,当输入无效输入时,它会正确打印我的错误消息,但当输入有效输入时,我必须输入两次才能中断循环。但是,如果我使用没有 || 的 while 循环它只需要一个值。

【问题讨论】:

  • 条件语句中的input.nextInt() 正在接受用户输入。
  • 您需要通过 do-while 循环更改您的 while 循环,并在您的 do-while 块中创建必要的条件。
  • 如果 nextInt() &lt;= options.length 那么你已经在条件中消耗(并丢弃)了它。您需要将该值保存在某处。

标签: java loops while-loop do-while


【解决方案1】:

您正在使用该值而不将其分配给变量。您可以像这样在循环条件中分配它:

while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length)

【讨论】:

  • 我将代码更改为while(!input.hasNextInt() || (proof = input.nextInt()) &gt; options.length) { String garbage = input.nextLine(); System.out.println("That input is not valid, try again"); } answer1 = input.nextInt(); 但是它仍然让我输入2个值以退出循环,不确定我是否错过了什么。
  • 我不知道proof 是什么。如果你的意思是answer1,则循环后不需要重复赋值。
【解决方案2】:

您正在 while 循环中使用扫描仪参数:

while(!input.hasNextInt()){
    int argument = input.nextInt();
    if(argument > options.length){
        System.out.println("That input is not valid, try again");
        continue; // get back to the start
    }
    // correctly handle your argument
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2013-09-16
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多