簡體   English   中英

循環無法正常工作

[英]A loop doesn't work properly

import java.util.*;

public class GuessNumber{
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        int x = 0;
        String num = "65854"; // This is the secret code
        String s;
        System.out.println("This program asks you to guess the code of 5 digits. ");
        System.out.println("You have 5 attempts. ");

        for(int i=0; i<5; i++){
            do{
                s = in.nextLine(); 


                for(int c=0; c<s.length(); c++){
                    if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
                        x++;
                }

                System.out.println("Number of correct digits in right position: " + x);  // here the execution goes out of bounds
            }
            while(!s.equals(num));
            System.out.println("Congrats! You guessed the secret code. ");
            System.exit(0);

        }
    }
}

我試圖創建一個簡單的 java 程序,它應該允許用戶猜測一個五位數的前綴代碼(只有五次嘗試)。 do-while 循環僅顯示前兩次嘗試的正確值,然后超出范圍(顯示值>5,這對於只有 5 位數字的代碼是不可能的)。 有人可以解釋為什么嗎?

刪除你的do-while循環。 它會一直運行,直到用戶猜出正確的代碼。
插入以下代碼以檢查字符串的長度

if(s.length()!=5){
    System.out.println("code should be of length 5");
    continue;
}

您可以為輸入字符串中的無字符添加更多限制。 每次都在外循環開始時重置x

還要檢查每個外循環中的輸入字符串是否正確

if(s.equals(num)){
    System.out.println("Congrats! You guessed the secret code. ");
    System.exit(0);
}

當前代碼-

for (int i = 0; i < 5; i++) {
    do {
         s = in.nextLine();
         for (int c = 0; c < s.length(); c++) { // the length of s can exceed 5 as of **num = "65854"**
             if (s.charAt(c) == num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
             x++;
             System.out.println("Number of correct digits in right position: " + x);
         }
      }
      while (!s.equals(num)); // this ensures currently N number of attempts NOT JUST 5 as stated otherwise.
      System.out.println("Congrats! You guessed the secret code. ");
      System.exit(0); // with this line the for loop would execute just once
}

建議代碼 -

String s;
int count = 0;
int x;
do {
    x = 0;
    if (count >= 5) { break; } // 5 attempts
    s = in.nextLine();
    String formattedNumber = String.format("%05d",
           Integer.parseInt(s)); // make sure the input is of 5 digit integer (padding here with 0's)
    for (int c = 0; c < formattedNumber.length(); c++) {
        if (formattedNumber.charAt(c) == num.charAt(c)) {
            x++;
        }
        if (x == 5) { // correct guess if all chars are equal
            System.out.println("Congrats! You guessed the secret code.");
            break; // break if guessed correct
        } else {
            System.out.println("Number of correct digits in right position: " + x);
        }
    }
    count++; //next attempt
} while (!s.equals(num)); //input not equals the desired, next attempt

自從您輸入真正的代碼以來,此代碼將永遠運行,因為您有do-while其條件說!s.equals(num) ,因此您必須首先刪除do-while ,這不是必需的,當您預測代碼等於num那么變量x必須等於5 ,因此您可以在打印成功后使用return語句終止程序。 注意x的值,每次迭代時它必須等於 0,我的意思是x=0

for(int i=0; i<5; i++){
    s = in.nextLine();
    if(s.length!=5){
       System.out.println("code should be of length 5");
       continue;
    }
    x = 0;
    for(int c=0; c<5; c++){
       if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
        x++;
    }
    System.out.println("Number of correct digits in right position: " + x);  // here the execution goes out of bounds
    if(x==5){
       System.out.println("Congrats! You guessed the secret code. ");
       return;
    }
}
System.out.println("Sryy !! :((");

暫無
暫無

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

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