2011-10-25 64 views
0

//通過:TLCJava,我將如何設置虛假輸入的循環?

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."); 

} 
} 

我將如何設置一個抓一個虛假的輸入(例如:不是一個整數),具有程序顯示錯誤消息後跟一個循環,將返回的開始程序?我一直在努力爭取一段時間。

所有幫助表示感謝! :)

回答

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"); 
    } 
} 

與前哨控制流(不與掃描儀的殼體2的方式但供將來參考)

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

使用try catch塊環繞以捕獲下一個值與整數正則表達式不匹配時引發的java.util.InputMismatchException。

Scanner API所述,在這些情況下,nextInt()方法將拋出此異常。