簡體   English   中英

為什么我的程序打印出異常語句會不斷給用戶帶來不好的輸入?

[英]Why does my program print out the exception statement endlessly give bad user input?

我不知道我的標題是否有意義,但這是代碼©

import java.util.InputMismatchException;
import java.util.Scanner;
public class Gussing {
    public static void theGame(Scanner input){
        int randomNum= (int)(Math.random()*101);//randomizes a number between 0-100 inclusive of both
        System.out.println(randomNum); //for debugging purposes
        int attemptCounter = 0; //counts how many attempts the user make
        System.out.print("Welcome to the guess-the number game! Enter your guess: ");

        while(true){
            System.out.println("here is bad input");
            try{
                System.out.println("here is after the bad input");
                int userInput= input.nextInt();
                if (userInput==randomNum) //when usr input and generated random number are equal we print how many attempts
                {
                    attemptCounter++;
                    System.out.println("Congrats you made the right guess after "+ attemptCounter + " attempts!");
                    break;

                }

                if(userInput<randomNum){
                    attemptCounter++;
                    System.out.print("Too low! Try again: ");

                    }
                else {
                    attemptCounter++; //else clause does the opposite of if clause
                    System.out.print("Too high! Try again: ");

                    }


                }
            catch( Exception e){
                    System.out.println("Invalid input");

                    }
            }

    }
    public static void main(String[] args){
        Scanner input = new Scanner (System.in);
        theGame (input);


        System.out.println("Play again? (Y/N)");

        try{
            char answer=input.next().toLowerCase().charAt(0);



            //toLowerCase method so that N =n = no !

            if (answer =='y') theGame (input);


            else if (answer =='n') System.out.println("Good bye");


            input.close(); //no more input data

            }
        catch(Exception e){
            System.out.println("invalid input");
        }
    }


}

因此,當在錯誤類型的用戶類型,即不int它打印出invalid input 但是,這不是問題,而是無限打印出來。 我嘗試調整try catch塊,但它根本沒有幫助

nextInt不會從輸入緩沖區中刪除非整數數據,因此除非消耗了數據,否則它將無限期地回收。 在這種情況下, InputMismatchException會拋出InputMismatchException ,因此您可以將異常塊編寫為

} catch (InputMismatchException e) {
    System.out.println("Invalid input " + input.nextLine());
}

暫無
暫無

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

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