简体   繁体   English

当用户输入字母或单词而不是预期的int(java)时,此程序将引发异常错误

[英]This program throws an exception error when the user inputs a letter or word instead of the expected int (java)

This program throws an exception error when the user inputs a letter by accident(typo) when they should enter a number. 当用户在输入数字时偶然输入了一个字母(错别字)时,该程序将引发异常错误。 I need to make it so the user(when asked to input a die number >=1) is able to accidentally enter something other than a number and have the program act like they never entered anything and open up the keyboard again.(while also displaying a message like, "You entered something wrong, please try again.") 我需要做到这一点,以便用户(当要求输入模具编号> = 1时)能够不小心输入数字以外的内容,并使程序的行为就像从未输入任何内容并再次打开键盘一样。显示类似“您输入了错误的消息,请重试”的消息。)

Heres the code: 这是代码:

import java.util.Scanner;

public class EnhancedGameOfPig {
    public static void main(String[] args) {


        //Scanner for taking input from keyboard
        Scanner kb = new Scanner(System.in);
        int nPlayer = 0;

        do
        {
            System.out.print("Enter the number of players (between 2 to 10): ");
            nPlayer = kb.nextInt();
            //validity checking for 2-10
             if (nPlayer<2 || nPlayer>10)
             {
                 System.out.println("Ops! the no of supported players are between 2 to 10");                    
                 System.out.println("Please enter again: ");
             }   

        }
        while(nPlayer<2 || nPlayer>10);
        //creating array of nPlayer as supplied by the user
        Player [] players = new Player[nPlayer];

        for(int i=0; i<nPlayer;i++){
            System.out.print("Enter player name: ");
            String name = new Scanner(System.in).nextLine();
            players[i] = new Player(name);

        }

        /*starting the game*/
        int round = 1;


        System.out.print("Enter predetermined win points: ");
        int GAME_OVER_POINT = new Scanner(System.in).nextInt();
        mark:
        while(true){

            //start round for each player
            for(int i=0;i<players.length;i++){
                System.out.println("Player Name: " + players[i].getName() + " you are playing round: " + round);

                System.out.print("Enter no of dies (>=1): ");
                int nDie = new Scanner(System.in).nextInt();
                //validity checking here for die, so that it is not <1
                if (!(nDie>=1)){
                    System.out.println("Oops! You need to enter a die that is greater than or equal to 1...");
                }
                //datastructure for holding dies for this ith player
                Die [] dieForPlayer = new Die[nDie];
                //create the die objects

                for(int k = 0;k<nDie;k++){
                    dieForPlayer[k] = new Die();
                }
                //rolling the dies now
                int totalValue = 0;
                boolean isThereOne = false;
                System.out.println("Rolling " + nDie + " for " + players[i].getName());
                for(int k = 0;k<dieForPlayer.length;k++){

                    int value = dieForPlayer[k].roll();
                    System.out.println(" Die No: " + (k+1) + " value: " + value);

                    if(value==1) //atleast one 1 is there
                        isThereOne = true;

                    totalValue += value;                                        
                }

                //roll is over.. now checking
                if (isThereOne && totalValue==nDie){
                    //all of  them 1
                    //reset the banked point for this player
                    players[i].resetBankedPoint();
                    System.out.println(players[i].getName() + "Oops! all the dies showed 1's\n "
                                                            + "You get nothing for this round and \n"
                                                            + "your banked point has been reset to 0");
                }
                else if (!isThereOne){
                    //no one(s) rolled
                    //add the points to the banked pont of the user
                    players[i].addBankedPoints(totalValue);
                    System.out.println(players[i].getName() + ", great! u get total of : " + totalValue + " for this round");
                    System.out.println("Your total Banked Point is: " + players[i].getBankedPoint());
                }
                else{
                    //there is atleast one 1, get no points for this round
                    players[i].addBankedPoints(0);
                    System.out.println(players[i].getName() + ", Sorry! one of the die turned with one! \n" +
                                                            "You get nothing for this round ");

                    System.out.println("Your total Banked Point is: " + players[i].getBankedPoint() + "\n");

                }


                if (players[i].getBankedPoint()>=GAME_OVER_POINT){
                    //the game over point has been reached, so breaking out of the outer while
                    break mark;
                }

            }

            round++;


        }//end of the undeterministic while 


        System.out.println("================The Game is Over=====================");
        System.out.println("Total Round played: " + round);
        System.out.println("=====================================================");
        for(int i=0;i<players.length;i++){
            System.out.print("Player Name: " + players[i].getName() + " Score: " + players[i].getBankedPoint());
            if(players[i].getBankedPoint()>=GAME_OVER_POINT){
                System.out.println(" WINNER");
            }
            else
                System.out.println();
        }
        System.out.println("======================================================");
        kb.close();


    }
}

If you use kb.nextLine() instead, it will return a String. 如果改为使用kb.nextLine() ,它将返回一个String。 Then use Integer.parseInt() within a try/catch block, to make sure your program doesn't break if it isn't a valid number. 然后在try / catch块中使用Integer.parseInt() ,以确保您的程序如果不是有效数字也不会中断。 You could do it like this: 您可以这样做:

String input = kb.nextLine();
int output = 0;
try {
    output = Integer.parseInt(input);
catch (NumberFormatException e) {
    System.out.println("Invalid input type");
}
if(kb.hasNextInt())
{
    // Do something
}
else
{
   System.out.println("You entered something wrong, please try again");
}

You could catch the InputMismatchException thrown if nextInt() is called and the next token is not an int. 如果调用nextInt()并且下一个标记不是int,则可以捕获抛出的InputMismatchException

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt() http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 取用户输入的单词的第一个字母,并在java中反复将其添加到末尾 - take the first letter of a word the user inputs and add it to the end repeatedly in java 用户输入字符而不是int时出错(Java) - Error when user enters a char instead of an int (Java) 如果用户输入 String 而不是 Int (JOptionPane),如何捕获错误 - How to catch an error if user inputs a String instead of Int (JOptionPane) Java 用户输入单词并使用“if”和“else”语句的程序,如果单词有偶数或奇数个字母 - Java Program where User inputs word and uses "if" and "else" statement if the word has an even or odd number of letters 运行JAVA程序时抛出EXCEPTION_ACCESS_VIOLATION - When running a JAVA program throws a EXCEPTION_ACCESS_VIOLATION 在Java中引发异常错误 - Throws Exception Error in Java 用户输入括号时Java程序出现异常 - Java program freaks out when user inputs parenthesis 程序正在运行,但当用户输入整数时出现错误 - Program is running but I get error when the user inputs integers 如果用户输入字母而不是数字,则告诉他们这不是数字 - if a user inputs a letter instead of a number tell them it's not a number 预期的; Java中用二进制值初始化int变量时出错 - expected ; error when initializing an int variable with binary value in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM