【问题标题】:not sure why while loop isn't looping不知道为什么while循环没有循环
【发布时间】:2021-10-21 14:53:35
【问题描述】:

我试图提示用户输入 5 个整数,但它不会循环多次。我不知道为什么会发生这种情况,并且我自己无法解决错误

代码:

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner s= new Scanner(System.in);

        int counter= 0;
        Boolean inputOK;
        int iInput;

        int data[]= new int[5];

       // while (counter<5);

     do {

         System.out.println(" Please enter an integer");

         while (!s.hasNextInt()) {
             System.out.println("Invalid input");
             System.out.println("Please Enter an integer value");
             s.next();}

            iInput=s.nextInt();

             if (iInput < -10 || iInput > 10) {
                 System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
                 inputOK = false;
             } else {
                 inputOK = true;

             }

         System.out.println("before while loop"+ inputOK);
         } while (!inputOK);
        counter++;
        System.out.println("counter value is"+ counter);



     }
}

【问题讨论】:

  • 你有一个计数器,但你没有使用它的循环。看起来你开始写一个,然后把它注释掉了。
  • 注意这个任务不需要使用do while循环,你可以使用简单的while loop。如果您的inputOK 为假,此while (!inputOK); 也会导致您的代码卡住并无限循环。最后,您只输入一个 int,因此循环只会运行一次 while (!s.hasNextInt()) ...
  • 嗨,凯文,欢迎来到 SO。我建议养成使用适当缩进的习惯。它不仅对于编写功能代码至关重要,而且还是与他人就您的代码进行交流的基础(例如在 SO 上,但在您的职业生涯后期,当许多其他人将阅读您的代码时)

标签: java while-loop do-while


【解决方案1】:

如果您遵循您的代码,您可以看到当inputOK 是true 时,没有循环可以返回。看起来你有一些计数器,但你最终没有使用它。以下代码符合我认为您对代码的意图:

Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
    System.out.println("Please enter an integer.");
    
    // Skip over non-integers.
    while(!sc.hasNextInt()) {
        System.out.println("Invalid input: " + sc.next());
    }
    
    // Read and store the integer if it is valid.
    int nextInt = sc.nextInt();
    if(nextInt < -10 || nextInt > 10) {
        
        // Make the for loop repeat this iteration.
        System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
        i--;
        continue;
    }
    data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
    System.out.println("data[" + i + "] = " + data[i]);
}

【讨论】:

    猜你喜欢
    • 2022-09-25
    • 2018-06-05
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多