2013-03-21 29 views
0

嗨即時嘗試創建一個代碼,我得到用戶輸入日期。然後,我將操縱這個日期來創建每天的旅行成本。我努力添加例外以防止輸入錯誤。任何人都可以給我一些關於如何做到這一點的提示?我的代碼:防止輸入錯誤時使用例外

import java.util.Calendar; 
import java.util.Date; 
import java.util.Scanner; 

public class Price 
{ 
    public static void main (String [] args) 
    { 
    userInput();   
    } 

    public static void userInput() 
    { 
    Scanner scan = new Scanner(System.in); 

    int month, day, year; 

    System.out.println("Please enter a month MM: "); 
    month = scan.nextInt(); 
    System.out.println("Please enter a day DD: "); 
    day = scan.nextInt(); 
    System.out.println("Please enter a year YYYY: "); 
    year = scan.nextInt(); 
    System.out.println("You chose: " + month + " /" + day + " /" + year); 
    } 
} 
+2

這不應該由異常處理,但通過簡單的測試/循環處理。請參閱Scanner javadoc中的'hasNextInt()'。 – 2013-03-21 22:27:00

回答

1

隱藏異常的方法內處理...

public static int inputInteger(Scanner in, String msg, int min, int max) { 
    int tries = 0; 
    while (tries < maxTries) { 
    System.out.println(msg); 
    try { 
     int result = in.nextInt(); 
     if (result < min || result > max) { 
     System.err.println("Input out of range:" + result); 
     continue; 
     } 
     return result; 
    } catch (Exception ex) { 
     System.err.println("Problem getting input: "+ ex.getMessage()); 
    } 
    } 
    throw new Error("Max Retries reached, giving up"); 
} 

這是一個有點簡單,但它是一個良好的開端簡單的應用程序。同類型的循環可以讓你驗證輸入(如不採取35日期)

0

可能是你應該使用IllegalArgumentException 這樣的:

if (month < 1 || month > 12 || day < 1 || day > 31) 
    throw new IllegalArgumentException("Wrong date input"); 

Exception基類:

if (month < 1 || month > 12 || day < 1 || day > 31) 
    throw new Exception("Wrong date input"); 

此外,您還可以創建您的Exception自己的子類:

class WrongDateException extends Exception 
{ 
    //You can store as much exception info as you need 
} 

,然後抓住它通過

try { 
    if (!everythingIsOk) 
     throw new WrongDateException(); 
} 
catch (WrongDateException e) { 
    ... 
} 
0

我只是把這些要求月份的第一次循環和別人同樣的步驟和同樣的想法,看到這一點:

int month, day, year; 
while(true){ 
    try{ 
System.out.println("Please enter a month MM: "); 
month=scan.nextInt(); 
if(month>0&&month<=12) 
    break; 
else System.err.println("Month should be between 1 and 12"); 
}catch(InputMismatchException ex){ 
    System.err.println(ex.getMessage()); 
    } 
} 
System.out.println("You chose: " + month); 
+0

掃描器拋出WrongInputException。 – 2013-03-21 22:39:03

+0

是的,謝謝@MelNicholson我不知道:) – Azad 2013-03-21 22:41:36

+0

任何方式'NumberFormatException'或'InputMismatchException'必須在這裏處理,因爲沒有打破環路,因爲mismatch災難錯誤:) – Azad 2013-03-21 22:47:56