0

我正在尝试循环异常,但由于某种原因,它没有给我重新编写扫描仪文件的选项:

我不知道如何使用 BufferedReader 所以这就是我使用它的原因。有什么线索吗?

这是我的标准课程和我的方法

package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {

    int firstInt;
    int secondInt;
    boolean error;
    Scanner yourNumbers = new Scanner(System.in);

    public void findNumbers()
    {
        System.out.println(" please enter your first number");
        firstInt = yourNumbers.nextInt();
        System.out.println(" pleas enter your second number");
        secondInt = yourNumbers.nextInt();
        int finalInt = (firstInt+secondInt);
        System.out.println("total is: " + finalInt);
    }
}

这是我的主要课程,例外是通过循环实现:

package arrayExceptionsWithInput;
import java.util.*;

public class InputException
{
    public static void main(String[] args)
    {
        boolean error = false;
        GetThoseNumbersBaby zack = new  GetThoseNumbersBaby();


        {
            do {
                try
                {
                    zack.findNumbers();
                }
                catch(InputMismatchException Q)
                {
                    System.out.println(" one of your integers was incorrect, please try again");
                    Q.printStackTrace();
                    error = true;
                } 
            } while (error == true);
        }
        error = false;
    }
}

如果有人对如何以不同方式循环播放有任何想法,我会全神贯注。

4

3 回答 3

1

在操作之前将错误设置为 false 。这样,如果用户正确,您就有正确的退出条件。

error = false;
zack.findNumbers(); 
于 2009-11-19T12:31:32.407 回答
0

我决定也摆脱方法类,只是将方法放入尝试异常区域。

在扫描仪之后使用了 .nextLine ,它似乎已修复。

这看起来不错?

package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
    do{
            try
            {

                    System.out.println(" please enter your first number");
                    firstInt = yourNumbers.nextInt();
                    yourNumbers.nextLine();
                    System.out.println(" pleas enter your second number");
                    secondInt = yourNumbers.nextInt();
                    yourNumbers.nextLine();
                    int finalInt = (firstInt+secondInt);
                    System.out.println("total is: " + finalInt);
                    yourNumbers.nextLine();

            }
            catch(InputMismatchException Q)
            {

                Q.printStackTrace();
                System.out.println(" one of your integers was incorrect, please try again");
                error = true;
                yourNumbers.nextLine();
            }   
        }while (error == true);
    }error = false;
}
}
于 2009-11-19T12:32:06.057 回答
0

你循环 while 'error'变量的值为'true'。但是,只有在抛出 时(即执行'catch'块时)它才会变为“真” 。控制流没有到达它。

于 2009-11-19T12:34:33.413 回答