2016-03-02 64 views
0

我是java新手,我試圖捕捉多個輸入語句的InputMismatchException。我意識到這是行不通的。我應該爲每個輸入語句單獨輸入catchtry嗎?嘗試並捕捉多個輸入語句

import java.util.InputMismatchException; 
import java.util.Scanner; 

public class Main { 

    public static void main(String[] args) { 
     // write your code here 
     Scanner input = new Scanner(System.in); 
     boolean tue = true; 
     int inputNum=0; 
     int inputNum2=0; 
     int inputNum3=0; 
     do { 
      try { 
       System.out.println("Enter a number"); 
       inputNum = input.nextInt(); 
       System.out.println("Enter another number: "); 
       inputNum2 = input.nextInt(); 
       System.out.println("Enter another number"); 
       inputNum3 = input.nextInt(); 
       tue = false; 

      } catch (InputMismatchException e) { 
       input.nextLine(); 
       System.out.println("Enter the require text"); 

      } 

     }while (tue); 
     System.out.println(inputNum + " "+ inputNum2 + " "+ inputNum3); 

    } 
} 
+0

這看起來OK,如果他們填滿了,那麼重新開始。 –

+0

究竟什麼是正常工作,你必須提供一個上下文 – osleonard

+0

當我輸入一個字符串兩次並輸入一個數字,它不能識別緊跟在字符串後面的數字。 – Intelligent

回答

0

我不知道是不是爲你工作,但這裏是我將如何實現這一點:

Scanner input = new Scanner(System.in); 
    int[] inputs = new int[3];//create array for the # of inputs 
    for (int i = 0; i < inputs.length;) { 
     try { 
      System.out.println("Enter Num " + (i + 1)); 
      inputs[i] = input.nextInt(); 
      i++;//only increment if the line above doesnt raise error 
     } catch (InputMismatchException e) { 
      input.nextLine(); 
      System.out.println("Only integers allowed, try again"); 
     } 
    } 
    input.close(); 
    System.out.println(inputs[0] + " " + inputs[1] + " " + inputs[2]); 

要打印整個數組:

for (int i = 0; i < inputs.length; i++) { 
     System.out.println(String.format("Input %s was %s", i + 1, inputs[i])); 
    }