2016-03-01 58 views
0

我想提示用戶輸入兩個數字,代表一塊板子的大小NxN。如果用戶寫入少於1個或多於2個數字,程序不允許他這樣做,而是由異常來處理。限制提示參數的數量

例如:

public class Tester { 

public static void main(String[] args) { 

    Scanner userInput = new Scanner(System.in); 

    System.out.print("Board size NxN: "); 

    int width = userInput.nextInt(); 
    int height = userInput.nextInt(); 
} 
} 

如何使用try-catch塊限制用戶僅輸入2號實現這一目標?

回答

0

公共類測試儀{

public static void main(String[] args) { 

    Scanner userInput = new Scanner(System.in); 

    System.out.print("Board size NxN: "); 
    try { 
     int width = userInput.nextInt(); 
     int height = userInput.nextInt(); 
     if (userInput.hasNext()) { 
      throw new IllegalArgumentException(); 
     } 
    } catch (IllegalArgumentException e) { 
     System.err.println("Enter just two numbers"); 
    } 
} 

}

+0

當我輸入第一個數字,然後是第二個,我按enter鍵,並繼續等待第三號。當第三個數字被放置時,它會拋出異常:板子尺寸NxN:2 3 「只輸入兩個數字」 –

+0

這是合乎邏輯的。您需要向用戶提示「Enter 1st」,「Enter 2nd」,「Correct(y/n)?」,並且只接受'YyNn'作爲最後一個輸入(並且只給第一個數字)。 –