我正在寫一個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){
....
}
請勿使用流量控制的異常。有更好的方法。順便說一句,你的ArrayList被稱爲「myArrayList」,而不是「整數」...如果這是你真正的代碼,我懷疑它編譯。 – Fildor
它不會編譯,catch語句的簽名也是不正確的。 – piechuckerr
「在輸入每個項目後,應該詢問用戶**,是否繼續輸入數據或退出應用程序。」 - 您可能想重新考慮這一點。想象一下,你必須輸入從0到346的所有整數,你不能輸入,而必須每次按「Y」。 – Fildor