9

これを行う方法はありますか?

//Example function taking in first and last name and returning the last name.
public void lastNameGenerator() throws Exception{
    try {
        String fullName = JOptionPane.showInputDialog("Enter your full name");
        String lastName = fullName.split("\\s+")[1];
    catch (IOException e) {
        System.out.println("Sorry, please enter your full name separated by a space.")
        //Repeat try statement. ie. Ask user for a new string?
    }
    System.out.println(lastName);

代わりにスキャナーを使用できると思いますが、例外をキャッチした後に try ステートメントを繰り返す方法があるかどうかに興味がありました。

4

9 に答える 9

9

このようなもの ?

while(condition){

    try{

    } catch(Exception e) { // or your specific exception

    }

}
于 2013-09-26T05:24:37.810 に答える
3

1 つの方法は、while ループを使用して、名前が適切に設定されたら終了することです。

boolean success = false;
while (!success) {
    try {
        // do stuff
        success = true;
    } catch (IOException e) {

    }
}
于 2013-09-26T05:26:24.600 に答える
1

他の人がすでに提案したように、言語には「再試行」はありません。外側のwhileループを作成し、再試行をトリガーする「catch」ブロックにフラグを設定します(試行が成功した後、フラグをクリアします)

于 2013-09-26T05:26:59.133 に答える
1

https://github.com/bnsd55/RetryCatchを使用できます

例:

RetryCatch retryCatchSyncRunnable = new RetryCatch();
        retryCatchSyncRunnable
                // For infinite retry times, just remove this row
                .retryCount(3)
                // For retrying on all exceptions, just remove this row
                .retryOn(ArithmeticException.class, IndexOutOfBoundsException.class)
                .onSuccess(() -> System.out.println("Success, There is no result because this is a runnable."))
                .onRetry((retryCount, e) -> System.out.println("Retry count: " + retryCount + ", Exception message: " + e.getMessage()))
                .onFailure(e -> System.out.println("Failure: Exception message: " + e.getMessage()))
                .run(new ExampleRunnable());

代わりにnew ExampleRunnable()、独自の無名関数を渡すことができます。

于 2018-09-08T13:38:22.737 に答える
0

showInputDialog() の署名は

public static java.lang.String showInputDialog(java.lang.Object message)
                                       throws java.awt.HeadlessException

そして、split() のそれは

public java.lang.String[] split(java.lang.String regex)

その後、どれもスローしませんIOException。じゃあどうやって捕まえるの?

とにかくあなたの問題に対する可能な解決策は

public void lastNameGenerator(){
    String fullName = null;
    while((fullName = JOptionPane.showInputDialog("Enter your full name")).split("\\s+").length<2)  {
    }
    String lastName =  fullName.split("\\s+")[1];
    System.out.println(lastName);
}

try-catch は必要ありません。自分で試しました。それは正常に動作します。

于 2013-09-26T05:39:37.197 に答える
0

再帰が必要です

public void lastNameGenerator(){
    try {
        String fullName = JOptionPane.showInputDialog("Enter your full name");
        String lastName = fullname.split("\\s+")[1];
    catch (IOException e) {
        System.out.println("Sorry, please enter your full name separated by a space.")
        lastNameGenerator();
    }
    System.out.println(lastName);
}
于 2013-09-26T05:24:54.600 に答える