Java 如何捕获hasNextInt()字符串输入异常?

Java 如何捕获hasNextInt()字符串输入异常?,java,exception,exception-handling,try-catch,Java,Exception,Exception Handling,Try Catch,在我的java应用程序(一个简单的TollMachine模拟器)中,我必须在代码中实现try/catch代码。我设法在hasNextInt提示符下处理字符串输入,但是当我尝试使用try/catch执行相同的操作时,我无法让程序进入catch部分。程序进入无限循环,我真的需要让它使用try/catch方法。否则,我使用if(hasNextInt)/else(变通方法)来摆脱字符串输入并防止无限循环 public class TollMachine { static boolean run

在我的java应用程序(一个简单的TollMachine模拟器)中,我必须在代码中实现try/catch代码。我设法在hasNextInt提示符下处理字符串输入,但是当我尝试使用try/catch执行相同的操作时,我无法让程序进入catch部分。程序进入无限循环,我真的需要让它使用try/catch方法。否则,我使用if(hasNextInt)/else(变通方法)来摆脱字符串输入并防止无限循环

public class TollMachine {

    static boolean running = true;  //variable to control whether the program should run
    static int userInput = -1;           //variable to store the user's input
    static String userInput2 = "";  //variable to store the input in case user does not enter an integer
    static int motoTicketCount = 0; //variable to store the number of tickets sold(moto)
    static int carTicketCount = 0;  //variable to store the number of tickets sold(car)
    static int vanTicketCount = 0;  //variable to store the number of tickets sold(van)
    static int truckTicketCount = 0;//variable to store the number of tickets sold(truck)
    static int totalTicketCount = 0;//variable to store the number of total tickets sold
    static Scanner keyb = new Scanner(System.in);   //variable to detect the user's input

    public static void main(String[] args) {

        while (userInput != 0) //runs while userInput != 0
        {

            //This is the main menu, the user is prompted to choose an option
            System.out.println("1. Motorcycle");
            System.out.println("2. Car");
            System.out.println("3. Van");
            System.out.println("4. Truck");
            System.out.println("5. Display total tickets sold.");
            System.out.println("0. Exit");

            try {

                if (keyb.hasNextInt())  //checks whether the user inputs an integer
                {

                    userInput = keyb.nextInt(); //stores the user's input to the userInput

                    if (userInput > 5 || userInput < 0)    //if one of these conditions are true, the user selected an option
                    {                                   //that is not mentioned
                        System.out.println("Invalid input.");   //displays the Invalid input error
                    } else {
                        //checks which option the user chose with multiple "if" conditions
                        if (userInput == 1) {
                            //Displays an appropriate message to the user, and increases the two counters by 1
                            System.out.println("Here is your motorcycle ticket.");
                            motoTicketCount++;
                            totalTicketCount++;
                        }
                        if (userInput == 2) {
                            //Displays an appropriate message to the user, and increases the two counters by 1
                            System.out.println("Here is your car ticket.");
                            carTicketCount++;
                            totalTicketCount++;
                        }
                        if (userInput == 3) {
                            //Displays an appropriate message to the user, and increases the two counters by 1
                            System.out.println("Here is your van ticket.");
                            vanTicketCount++;
                            totalTicketCount++;
                        }
                        if (userInput == 4) {
                            //Displays an appropriate message to the user, and increases the two counters by 1   
                            System.out.println("Here is your truck ticket.");
                            truckTicketCount++;
                            totalTicketCount++;
                        }
                        if (userInput == 5) {
                            //Displays how many of each ticket were sold, and the total number of tickets sold
                            System.out.println("Motorcycle tickets sold: " + motoTicketCount);
                            System.out.println("Car tickets sold: " + carTicketCount);
                            System.out.println("Van tickets sold: " + vanTicketCount);
                            System.out.println("Truck tickets sold: " + truckTicketCount);
                            System.out.println("Total tickets sold: " + totalTicketCount);
                        }
                        if (userInput == 0) {
                            running = false;    //terminates the program
                        }
                    }//end of else after the if (hasNextInt())

                }//end of first if (hasNextInt())                                         

            }//end of try

            catch (Exception e)    //this SHOULD catch an invalid input error
            {
                System.out.println("Invalid input.");  //displays invalid input in case the
                userInput2 = keyb.next();              //discard the bad input
            }
        }
    }
}
公共类收费机{
static boolean running=true;//用于控制程序是否应运行的变量
static int userInput=-1;//用于存储用户输入的变量
静态字符串userInput2=“”;//在用户未输入整数的情况下存储输入的变量
static int motoTicketCount=0;//用于存储已售出票数(moto)的变量
static int carTicketCount=0;//用于存储售出车票数量(车)的变量
static int vanTicketCount=0;//用于存储已售出车票(van)数量的变量
静态int-truckTicketCount=0;//用于存储已售出车票数量(卡车)的变量
静态int totalTicketCount=0;//用于存储已售出总票数的变量
static Scanner keyb=new Scanner(System.in);//用于检测用户输入的变量
公共静态void main(字符串[]args){
while(userInput!=0)//在userInput!=0时运行
{
//这是主菜单,提示用户选择一个选项
系统输出打印(“1.摩托车”);
System.out.println(“2.Car”);
System.out.println(“3.Van”);
系统输出打印(“4.卡车”);
System.out.println(“5.显示售出的总票数”);
System.out.println(“0.Exit”);
试一试{
if(keyb.hasNextInt())//检查用户是否输入整数
{
userInput=keyb.nextInt();//将用户的输入存储到userInput
if(userInput>5 | | userInput<0)//如果这些条件之一为真,则用户选择了一个选项
{//没有提到这一点
System.out.println(“无效输入”);//显示无效输入错误
}否则{
//使用多个“如果”条件检查用户选择的选项
if(userInput==1){
//向用户显示适当的消息,并将两个计数器增加1
System.out.println(“这是你的摩托车票。”);
motoTicketCount++;
totalTicketCount++;
}
if(userInput==2){
//向用户显示适当的消息,并将两个计数器增加1
System.out.println(“这是你的车票。”);
carTicketCount++;
totalTicketCount++;
}
if(userInput==3){
//向用户显示适当的消息,并将两个计数器增加1
System.out.println(“这是你的货车票。”);
vanTicketCount++;
totalTicketCount++;
}
if(userInput==4){
//向用户显示适当的消息,并将两个计数器增加1
System.out.println(“这是你的卡车票。”);
truckTicketCount++;
totalTicketCount++;
}
if(userInput==5){
//显示每张票的售出数量以及售出的总票数
System.out.println(“摩托车票售出:+motoTicketCount”);
System.out.println(“售出车票:+carTicketCount”);
System.out.println(“售出的客票:+vanTicketCount”);
System.out.println(“售出的卡车票:+truckTicketCount”);
System.out.println(“售出总票数:+totalTicketCount”);
}
if(userInput==0){

running=false;//终止程序 } }//if(hasNextInt())后面的else结束 }//第一个if的结束(hasNextInt()) }//尝试结束 catch(异常e)//这应该捕获无效的输入错误 { System.out.println(“无效输入”);//在 userInput2=keyb.next();//放弃错误的输入 } } } }
在这里:

                if (userInput >5 || userInput<0)    //if one of these conditions are true, the user selected an option
                {                                   //that is not mentioned
                    System.out.println("Invalid input.");   //displays the Invalid input error
                }
编辑:为了尝试理解异常的概念,我建议您尝试将输入检查更改为
if(keyb.hasNext())
,然后尝试使用
integer.parseInt(keyb.next())将输入转换为整数并捕获结果
NumberFormatException

此外,您可以只设置
userInput=-1,而不是使用
userInput2
变量来存储错误数据
重新启动catch函数中的循环

完整代码:

public class TollMachine 
{

static boolean running = true;  //variable to control whether the program should run
static int userInput = -1;           //variable to store the user's input
static String userInput2 = "";  //variable to store the input in case user does not enter an integer
static int motoTicketCount = 0; //variable to store the number of tickets sold(moto)
static int carTicketCount = 0;  //variable to store the number of tickets sold(car)
static int vanTicketCount = 0;  //variable to store the number of tickets sold(van)
static int truckTicketCount = 0;//variable to store the number of tickets sold(truck)
static int totalTicketCount = 0;//variable to store the number of total tickets sold
static Scanner keyb = new Scanner(System.in);   //variable to detect the user's input

public static void main(String[] args)
{

    while (userInput != 0) //runs while userInput != 0
    {

        //This is the main menu, the user is prompted to choose an option
        System.out.println("1. Motorcycle");
        System.out.println("2. Car");
        System.out.println("3. Van");
        System.out.println("4. Truck");
        System.out.println("5. Display total tickets sold.");
        System.out.println("0. Exit");

        try
        {
            /**
            THIS THROWS YOUR EXCEPTION
            **/
            if (keyb.hasNext())  
            {

                userInput = Interger.parseInt(keyb.next()); //stores the user's input to the userInput

                if (userInput >5 || userInput<0)    //if one of these conditions are true, the user selected an option
                {                                   //that is not mentioned
                    System.out.println("Invalid input.");   //displays the Invalid input error
                }
                else
                {
                    //checks which option the user chose with multiple "if" conditions
                    if (userInput == 1)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your motorcycle ticket.");
                        motoTicketCount++;   
                        totalTicketCount++;

                    }
                    if (userInput == 2)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your car ticket.");
                        carTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 3)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your van ticket.");
                        vanTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 4)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1   
                        System.out.println("Here is your truck ticket.");
                        truckTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 5)
                    {

                        //Displays how many of each ticket were sold, and the total number of tickets sold
                        System.out.println("Motorcycle tickets sold: "+motoTicketCount);
                        System.out.println("Car tickets sold: "+carTicketCount);
                        System.out.println("Van tickets sold: "+vanTicketCount);
                        System.out.println("Truck tickets sold: "+truckTicketCount);
                        System.out.println("Total tickets sold: "+totalTicketCount);

                    }
                    if (userInput == 0)
                    {

                        running = false;    //terminates the program

                    }
                }//end of else after the if (hasNextInt())

             }//end of first if (hasNextInt())                                         

        }//end of try

        catch (NumberFormatException e)    //this SHOULD catch an invalid input error
        {
            System.out.println("Invalid input.");  //displays invalid input in case the
            userInput = -1;
        }

    }

}



}
公共类收费机
{
static boolean running=true;//用于控制程序是否应运行的变量
static int userInput=-1;//用于存储用户输入的变量
静态字符串userInput2=“”;//sto的变量
public class TollMachine 
{

static boolean running = true;  //variable to control whether the program should run
static int userInput = -1;           //variable to store the user's input
static String userInput2 = "";  //variable to store the input in case user does not enter an integer
static int motoTicketCount = 0; //variable to store the number of tickets sold(moto)
static int carTicketCount = 0;  //variable to store the number of tickets sold(car)
static int vanTicketCount = 0;  //variable to store the number of tickets sold(van)
static int truckTicketCount = 0;//variable to store the number of tickets sold(truck)
static int totalTicketCount = 0;//variable to store the number of total tickets sold
static Scanner keyb = new Scanner(System.in);   //variable to detect the user's input

public static void main(String[] args)
{

    while (userInput != 0) //runs while userInput != 0
    {

        //This is the main menu, the user is prompted to choose an option
        System.out.println("1. Motorcycle");
        System.out.println("2. Car");
        System.out.println("3. Van");
        System.out.println("4. Truck");
        System.out.println("5. Display total tickets sold.");
        System.out.println("0. Exit");

        try
        {
            /**
            THIS THROWS YOUR EXCEPTION
            **/
            if (keyb.hasNext())  
            {

                userInput = Interger.parseInt(keyb.next()); //stores the user's input to the userInput

                if (userInput >5 || userInput<0)    //if one of these conditions are true, the user selected an option
                {                                   //that is not mentioned
                    System.out.println("Invalid input.");   //displays the Invalid input error
                }
                else
                {
                    //checks which option the user chose with multiple "if" conditions
                    if (userInput == 1)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your motorcycle ticket.");
                        motoTicketCount++;   
                        totalTicketCount++;

                    }
                    if (userInput == 2)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your car ticket.");
                        carTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 3)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1
                        System.out.println("Here is your van ticket.");
                        vanTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 4)
                    {

                        //Displays an appropriate message to the user, and increases the two counters by 1   
                        System.out.println("Here is your truck ticket.");
                        truckTicketCount++;
                        totalTicketCount++;

                    }
                    if (userInput == 5)
                    {

                        //Displays how many of each ticket were sold, and the total number of tickets sold
                        System.out.println("Motorcycle tickets sold: "+motoTicketCount);
                        System.out.println("Car tickets sold: "+carTicketCount);
                        System.out.println("Van tickets sold: "+vanTicketCount);
                        System.out.println("Truck tickets sold: "+truckTicketCount);
                        System.out.println("Total tickets sold: "+totalTicketCount);

                    }
                    if (userInput == 0)
                    {

                        running = false;    //terminates the program

                    }
                }//end of else after the if (hasNextInt())

             }//end of first if (hasNextInt())                                         

        }//end of try

        catch (NumberFormatException e)    //this SHOULD catch an invalid input error
        {
            System.out.println("Invalid input.");  //displays invalid input in case the
            userInput = -1;
        }

    }

}



}