簡體   English   中英

不知道為什么 while 循環不循環

[英]not sure why while loop isn't looping

我試圖提示用戶輸入 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);



     }
}

如果你按照你的代碼,你可以看到當inputOKtrue ,沒有循環可以返回。 看起來你有一些計數器,但你最終沒有使用它。 以下代碼執行我認為您對代碼的意圖:

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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM