当前位置: 代码迷 >> java >> 捕获两个异常:字符串(需要Int时)和Int超出参数时
  详细解决方案

捕获两个异常:字符串(需要Int时)和Int超出参数时

热度:74   发布时间:2023-07-16 17:52:53.0

我对Java编程(以及一般编程)非常陌生。 我一直在搜寻google,却无法找到我的问题的答案。

我只想编写程序,除了他们的汽车年份在1940年至2016年之间。我还希望该程序能够在用户输入字符串而不是int时捕获。 在针对这两种情况抛出错误消息之后,我想问用户再次输入汽车的年份,直到他们输入正确的年份。 任何帮助,将不胜感激。 谢谢!

这是我的代码:

import java.util.*;
public class CarPractice 
{
    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System.in);
        int year;

        try
        {
            System.out.println("Enter your cars year");
            year = keyboard.nextInt();
            if  (year < 1940 || year > 2016)
                throw new Exception("You have entered a year that is not within the parameters of this program. Please enter a year betwee 1940 and 2016.");
            System.out.println("The year of your car is: " + year +".");
        }                                        
        catch(InputMismatchException e)
        {
            System.out.println("\t** You have entered an invalid input. Please enter a number and then try again.");
        }
        catch(Exception e)
        {

        }

    } 
}

您可以尝试以下程序。

package com.java.test;

import java.util.Scanner;

public class CarPractice 
{
    private static final int YEAR_LOWER_LIMIT = 1940;
    private static final int YEAR_UPPER_LIMIT = 2016;

    public static void main(String[] args) 
    {
        int year = 0;
        Scanner userInput = null;
        boolean isCorrectInput = false;
        try
        {
            while(!isCorrectInput)
            {
                isCorrectInput = true;
                System.out.println("Enter your cars year:");
                userInput = new Scanner(System.in);
                try
                {
                    year = Integer.parseInt(userInput.next());
                    if(year < YEAR_LOWER_LIMIT|| year > YEAR_UPPER_LIMIT)
                    {
                        System.out.println("You have entered an incorrect year. Year should be in between 1940 and 2016. Please enter a correct year:");
                        isCorrectInput = false;
                    }
                }
                catch(NumberFormatException nfe)
                {
                    System.out.println("You have entered an incorrect year. Please enter a correct year:");
                    isCorrectInput = false;
                }
            }
            System.out.println("Year is :"+year);
        }
        finally
        {
            if(userInput != null)
            {
                userInput.close();
            }
        }   
    }  
}

注意:

  • 使用单个类时,请勿导入整个程序包。 这将是编译器的负担。 (例如,不要使用import java.util.*;而应使用import java.util.Scanner;

  • 不要硬编码代码中的值。 如果它是常量,则将其声明为常量并使用。 (例如,不要将值1940硬编码为一个有意义的常量名(例如1940 YEAR_LOWER_LIMIT )。从长远来看,这种做法将节省您在大型模块上工作的时间和头痛。

  相关解决方案