我对Java编程(以及一般的编程)非常陌生。我一直在搜索谷歌,但一直无法找到我的问题的答案。
我正在努力制作我的程序,除了他们的汽车年份在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)
{
}
}
}
答案 0 :(得分:0)
您可以尝试以下程序。
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.*;
)
java.util.Scanner;
不要对代码中的值进行硬编码。如果它是常量,则将其声明为常量并使用。 (例如,不要对值1940
进行硬编码,而是将其声明为一个有意义的常量名称(例如YEAR_LOWER_LIMIT
的{{1}})。从长远来看,这种做法可以节省您的时间和头痛在处理大型模块时。