我想在我的代码
中抛出异常后重新启动程序 System.out.println("please enter an intger to compute its factorial:");
BufferedReader bufferedreader = new BufferedReader( new InputStreamReader(System.in));
String number ="";
try {
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("error you should enter a number");
throw new MyExceptions("try again please use integer numbers");
//if possible to restart the main
}
所以当用户输入一个字符时,程序会抛出一个异常,然后重新启动就可以了吗?
答案 0 :(得分:2)
通常,不应该递归地调用main
,尤其是为了重新启动程序。
如果要返回程序中的某个点,请使用循环。以下是您可以执行此操作的一个示例:
boolean done = false;
do {
done = true;
try {
...
} catch (NumberFormatException e) {
System.out.println("error you should enter a number");
done = false;
}
} while (!done);
每次异常处理程序将done
设置为false
时,循环将从头开始继续。
答案 1 :(得分:0)
你可以把它放在一个循环中。
While(isValid != TRUE)
{
try
{
try {
number = bufferedreader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
intN=Integer.parseInt(number);
if (intN > 0) { // from the command line
FactorialIter f =
new FactorialIter(Math.abs(intN));
isValid = TRUE;
}
}
catch (NumberFormatException e)
{
System.out.println("error you should enter a number");
System.out.println("try again please use integer numbers");
isValid = FALSE;
}
}