2017-03-23 24 views
-1

我正在寫一個Java應用程序,它允許用戶輸入一些整數值並將它們插入ArrayList中。應在輸入每個項目後詢問用戶是否繼續輸入數據或退出應用程序。正確實現try/catch語句與整數ArrayLists

以及我必須輸入一個double值才能看到拋出的異常類型。一旦確定,編寫Try/Catch語句來處理特定的異常,並允許用戶繼續輸入數據(而不是讓應用程序崩潰)。

這是我到目前爲止有:

import java.util.Scanner; 
import java.util.ArrayList; 

public class Tester{ 
    public static void main(String[] args){ 
    ArrayList<Integer> myArrayList = new ArrayList<Integer>(); 
    Scanner input = new Scanner(System.in); 
    while (true) { 
     System.out.println("please enter an integer: "); 
     integer.add(input.next()); 

到目前爲止,我已經創造了ArrayList和提示進行用戶輸入的,現在我在與繼續要求用戶輸入或詢問的麻煩他們停止這個過程(我該怎麼做?)

另外我該如何編寫try/catch塊部分?我明白'try'部分必須包含可能導致異常的語句。所以,我怎麼能寫這樣的:

try { 
    if input = double 
    System.out.print("This is an error")? 
} 

catch(inputMismatchexception e){ 
.... 
} 
+0

請勿使用流量控制的異常。有更好的方法。順便說一句,你的ArrayList被稱爲「myArrayList」,而不是「整數」...如果這是你真正的代碼,我懷疑它編譯。 – Fildor

+0

它不會編譯,catch語句的簽名也是不正確的。 – piechuckerr

+0

「在輸入每個項目後,應該詢問用戶**,是否繼續輸入數據或退出應用程序。」 - 您可能想重新考慮這一點。想象一下,你必須輸入從0到346的所有整數,你不能輸入,而必須每次按「Y」。 – Fildor

回答

0

這是你所需要的:

try{ 
    myArrayList.add(input.nextInt()); 
}catch(InputMismatchException e){ 
} 
catch(NoSuchElementException e1){ 
} 
    catch(IllegalStateException e2){ 
} 

這將引發InputMismatchError如果輸入不是一個整數,從而覆蓋你的雙輸入性病例。

之後,只需提示用戶確認他們是否要繼續(類似於Ravi在他的回答中所寫的內容)。

0

我在與繼續要求用戶輸入或要求 他們停止過程

內部while循環麻煩

System.out.println("Do you want to continue ?? (Y/N) "); 
String str = input.next(); 
if(str.equals("N") 
{ 
break; 
} 
0

input.next()總是給你一個字符串,所以你需要做的是使用Integer.parseInt(input)並檢查NumberFormatException

import java.util.Scanner; 
import java.util.ArrayList; 

public class Tester{ 
    public static void main(String[] args){ 
    ArrayList<Integer> myArrayList = new ArrayList<Integer>(); 
    Scanner input = new Scanner(System.in); 
    while (true) { 
     System.out.println("please enter an integer: "); 
     try { 
      int value = Integer.parseInt(input.next()); 
      myArrayList.add(value); 
     } catch (NumberFormatException e) { 
      // TODO whatever you want to do here 
     } 
    } 
} 
+0

確實如此,修正了它。謝謝 :) –

0

你要下來錯誤路徑:您要使用例外控制程序的流動

這是可能的;但在java中不被視爲「良好實踐」。

顧名思義,例外情況是例外(又名錯誤)的情況。但用戶想要停止該程序 - 這不是一件特殊的事情;那應該是核心你邏輯的一部分!

從這個意義上說:只需使用Scanner對象向用戶詢問字符串。在將這些字符串轉換爲數字之前;例如,你可以檢查字符串是否爲空。或者如果字符串是equalIgnoreCase()以「退出」。允許用戶通過點擊「輸入」或鍵入「退出」來停止程序。

備案:您也可以使用例外;只需要Integer.parseInt(「任何不是int數字的字符串」)都會拋出NumberFormatException異常。

但正如說:捕捉那些並假設用戶這樣做的目的是爲了結束這個循環是一個不好的想法。如果用戶不注意,該怎麼辦?犯了一個錯字,不想停下來?!如果你告訴他「你沒有輸入一個有效的號碼,再試一次」不是更好嗎?