代码 在输入时运行后抛出这些异常 第一个输入正常工作但第二个输出异常
sample output should be like this
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at WeatherEngine.WeatherRecord(WeatherEngine.java:53)
at WeatherProcessingSystem.main(WeatherProcessingSystem.java:36)
WARNING: process exited with a(n) Unknown (1) error code
主要方法
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice=0;
boolean flag = true;
WeatherEngine weather = new WeatherEngine();
System.out.println("Welcome to Weather Data Processing System!"
+"\nYou can process weather information using this system.\n"
+"\nPlease select a feature you wish to use from the following:\n");
do{
System.out.println("1. \t Weather Record"
+"\n2. \t Averages"
+"\n3. \t Maximums"
+"\n4. \t Minimums"
+"\n5. \t Total Precipitation"
+"\n6. \t Extremes"
+"\n0. \t Quit");
do{
try{
flag=false;
choice = scan.nextInt();
if(choice<0||choice>6)
throw new Exception();
}catch(Exception e){
System.out.println("Wrong input \n Enter again");
scan.next();
flag=true;
}
}while(flag);
flag = true;
switch(choice){
case 1:{
weather.WeatherRecord();
break;
}
case 2:{
weather.Average();
break;
}
case 3:{
weather.Maximum();
break;
}
case 4:{
weather.Minimum();
break;
}
case 5:{
weather.TotalPrecipitation();
break;
}
case 6:{
weather.Extremes();
}
default:{
flag = false;
}
}
}while(flag);
}
weatherRecord方法
public void WeatherRecord(){
boolean flag=true;
do{
try{
flag=false;
System.out.println("Enter date in MM/DD/2008");
String str = scan.next();
System.out.println(str);
String [] str2 =str.split("/");
int a = Integer.parseInt(str2[0])-1;
int b = Integer.parseInt(str2[1])-1;
for(int i=0;i<4;i++){
System.out.printf("Loaction: %3s \t\t Date: %2s %2d,2008 \n",wrec[i][a][b].getlocation(),mon[a],(b+1));
System.out.printf("High Temp: %3d \t\t\t Low Temp: %3d \n",wrec[i][a][b].getHigh(),wrec[i][a][b].getLow());
System.out.printf("Avg Wind: %3d \t\t\t Max Wind %3d\n",wrec[i][a][b].getWinds(),wrec[i][a][b].getGusts());
System.out.printf("Precipitaion: %3.2f inches\n \n",wrec[i][a][b].getPrecip());
}
}catch(Exception e){
System.out.println("Wrong input \n Enter again");
scan.next();
flag=true;
}
}while(flag);
}
答案 0 :(得分:0)
if (scan.hasNext())
String str = scan.next();
答案 1 :(得分:0)
或者更简洁,你不应该像你那样使用异常。
do {
choice = scan.nextInt();
flag = choice < 0 || choice > 6
if (flag)
System.out.println("Wrong input \n Enter again");
} while(flag);