我正在編寫一些Java代碼,如果發現異常,我想循環回到較早的方法。Java:如何在吞嚥後調用以前的方法異常
這裏是一個簡化版本的我的代碼:
public class classA
{
public static void main(String[] args)
{
int number1 = askUserForFavoriteSum();
int number2 = askUserForAnotherNumber();
}
public static int askUserForFavoriteSum()
{
int firstFavorite;
int secondFavorite;
int favoriteSum
System.out.println("What is your first favorite number?");
firstFavorite = classB.getIntFromConsole();
System.out.println("What is your second favorite number?");
secondFavorite = classB.getIntFromConsole();
favoriteSum = firstFavorite + secondFavorite;
return favoriteSum;
}
public static int askUserForAnotherNumber()
{
int number;
System.out.println("What is another number?");
number = classB.getIntFromConsole();
return number;
}
}
public class classB
{
public static int getIntFromConsole()
{
Scanner scanner = new Scanner(System.in)
int value;
try
{
value = Integer.valueOf(scanner.nextLine());
}
catch (NumberFormatException e) //Occurs when the input string cannot cleanly be converted to an int.
{
System.out.println("ERROR: Invalid input! Please enter a whole number.");
}
return value;
}
}
例如,鑑於上述兩個班,我想下面的情況發生:
- askUserForFavorite方法被執行。
- 用戶在提示輸入他們的第一個最喜歡的號碼時輸入「Potatoe」。因此,發生NumberFormatException。
- 「錯誤:輸入無效!請輸入一個整數。」打印到 控制檯。
- askUserForFavorite方法被執行(再次)。 這就是我正在努力的。
- 用戶在提示輸入最愛號碼時輸入「2」。因此,不會發生 異常。
做了一些研究之後,我看到很多人用Strategy Design Pattern去,然而,這並不適合我,因爲我有動態變量在我的ClassA的方法和接口不符合動態變量發揮出色。
在其他情況下,某些開發人員會將「Callable < MethodReturnType>」參數傳遞給它的等效方法,並調用未來的方法來反映傳入的方法。這種方法看起來好像可行,但它需要我添加一個新的抽象層。
有沒有一種方法可以簡單地調用classA中調用我的getIntFromConsole方法的前一個方法,而無需添加抽象層或接口?
使用while循環(即'而(無效){askForIt}') – 2017-02-16 06:11:27
你可以讓'getIntFromConsole'拋出'NumberFormatException'進一步(可能包裝成一個更好的-suited'Exception'),在'main'中捕獲它,然後重試(例如使用循環)。 – yeputons