Java,我如何为错误输入设置循环?

时间:2011-10-25 23:25:53

标签: java

// by:tlc

import java.util.Scanner;
public class assignment2 {
public static int t1;
public static int t2;
public static int x;
public static int y1;
public static int m1;
public static int d1;
public static int y2;
public static int m2;
public static int d2;
public static void date1() {

Scanner scanner  = new Scanner (System.in);

System.out.println("Please enter the first date \n");
System.out.println ("Please enter the year: "); 
y1=scanner.nextInt();

System.out.println("Please enter the month: ");
m1=scanner.nextInt();

System.out.println("Please enter the day: \n");
d1=scanner.nextInt();

}
public static void date2() {
Scanner scanner  = new Scanner (System.in);

System.out.println("Please enter the second date \n");
System.out.println ("Please enter the year: "); 
y2=scanner.nextInt();

System.out.println("Please enter the month: ");
m2=scanner.nextInt();

System.out.println("Please enter the day: \n");
d2=scanner.nextInt();

}
public static void finaldate() {
x = Math.abs(t1-t2);
}
public static void main(String[] args) {    
date1();
    if (m1==1 + 3 + 5 + 7 + 8 + 10 + 12){
        t1 = ((365*y1)+d1+31);}
        else 
        if (m1==2) {
        t1 = ((365*y1)+d1+28);}
        else
        if (m1==4 + 6 + 9 + 11); {
        t1 = ((365*y1)+d1+30);}

 date2();
    if (m2==1 + 3 + 5 + 7 + 8 + 10 + 12){
        t2 = ((365*y2)+d2+31);}
        else 
        if (m2==2) {
        t2 = ((365*y2)+d2+28);}
        else
        if (m2==4 + 6 + 9 + 11); {
        t2 = ((365*y2)+d2+30);}
 finaldate();

 System.out.println("The difference between the two dates is: " + x + " days.");

}
}

我如何设置一个错误的输入(例如:不是整数)并让程序显示一条错误信息,然后是一个循环,返回程序的开头?我一直在努力解决这个问题。

所有帮助表示赞赏! :)

2 个答案:

答案 0 :(得分:1)

使用try catch块进行环绕以捕获当下一个值与整数正则表达式不匹配时抛出的java.util.InputMismatchException。

正如Scanner API中所述,nextInt()方法会在这些情况下抛出此异常。

答案 1 :(得分:0)

有两种方式取决于控制流的管理方式

作为控制流的例外(扫描仪的情况)

while(true){
    try{
        y1=scanner.nextInt();
        break;//success break out of loop
    }catch(InputMismatchException e){
        System.out.println("incorrect input! \n");
        System.out.println("Please enter the second date \n");
    }
}

以哨兵作为控制流程(不是扫描仪的情况,但供将来参考)

while((y1=scanner.nextInt())!=-1){
    System.out.println("incorrect input! \n");
    System.out.println("Please enter the second date \n");
}