簡體   English   中英

Java異常處理循環錯誤

[英]Java Exception handling looping error

我想盡一切辦法幫助

當我嘗試1/4鍵入字母時,它可以正常工作並繼續,但是一旦我嘗試2/4鍵入字母,它只會打印該消息,並且程序停止。 還有關於#2的任何提示,我只能想到if(guess> = 4 &&猜測<= 16)else語句(不確定這是否正確)

當我執行代碼時-

Guess a number between 1 and 16.

Attempt 1 of 4: 8

You guessed 8

Too Low! 

Attempt 2 of 4: a

Please enter an integer between 4-16     

之后不能輸入任何內容

問題:如果用戶鍵入

1)非數字輸入

2)超出范圍輸入

3)必須保留當前的猜測量

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class GuessingGame {

static final int limit = 4;
static final int maxInteger = 16;

public static void main(String[] args) {

Random rand = new Random();
int target = rand.nextInt(maxInteger) + 1;
int x = 1;

    do{
    try{
        Scanner input = new Scanner(System.in);
        System.out.printf("Guess a number between 1 and %d.\n", maxInteger);


    int attempts = 1;
    while (attempts <= limit) {
        System.out.printf("Attempt %d of %d: ", attempts, limit);


        int guess = input.nextInt();
        System.out.printf("You guessed %d\n", guess);

        if(guess > target) {
        System.out.printf("Too High! \n");

        }
        else if(guess == target){

        System.out.printf("The answer is %d, You win!", guess);
            attempts = 20;

        }
        else{
        System.out.printf("Too Low! \n");

        }

        attempts+=1;
        x = 2;
    }
    if(attempts==5){
    System.out.println("You lose!");
    }
    }
    catch(InputMismatchException e){
        System.out.printf("Please enter an integer between 4-16");
        continue;


    }
    }while(x == 1);
}
}

您正在檢查while(x == 1); 在外循環和內循環中,通過使x = 2;增加x的值x = 2; 這將破壞條件,您將退出外部while循環。

如果要繼續,則應該為外部while循環設置有效條件。 試試while(x < 5);

您的代碼應如下所示:

do {
    try {
        ...
        /* Inner While */
        while() {}
        ...
    } catch () {
        /* Exception Handling */
        ...
    }
} while(x < 5); /* Decide a valid condition */

1)嘗試將try catch塊移動到內部循環中,以便僅將其圍起來

int guess = input.nextInt();

2)您對第2條的想法應該可行。

if(guess>=4 && guess<=16)

確保這是檢查中的第一個if語句,那么您不必更改其他任何if語句。

3)在兩個循環外都創建一個稱為guess的變量,然后不要說

int guess = input.nextInt();

說啊

guess = input.nextInt();

在您更新之前,您將可以使用當前的猜測。

4)您的變量x令人困惑。 您是否將其用作結束外部循環的標志? 如果是這樣,請將其設為布爾值

boolean flag = true;

那么當您准備好退出循環時,可以將標志設置為false。 更改

x = 2;

flag = false;

也為循環所有變化

while(x==1)

while(flag)

暫無
暫無

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

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