package simple;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class AreaofCircle{
public static void main(String args[]){
float PI = 3.1416f;
int r=0;
String rad;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Radius?");
try{
rad = br.readLine();
r = Integer.parseInt(rad);
System.out.println("Circle area is: " + PI*r*r + " Permieter: " +PI*2*r);
}
catch(Exception e){
System.out.println("Write an integer number");
AreaofCircle a = new AreaofCircle();
}
}
}
在这段代码中,假设用户使用键盘输入一些字符串,在try块中它显示异常并且它来到catch块,
我希望显示错误的详细信息,并希望再次将用户推回到该代码,这是怎么回事,Plz帮我解决了这个问题。
答案 0 :(得分:2)
int allowedAttempts=0;
while(true)
{
try{
rad = br.readLine();
r = Integer.parseInt(rad);
System.out.println("Circle area is: " + PI*r*r + " Permieter: " +PI*2*r);
break;
}
catch(Exception e){
System.out.println("Write an integer number");
allowedAttempts++;
if(allowedAttempts==3){
System.out.println("No More attempts allowed");break;
}
}
}
您可以使用整数变量,并提示特定次数的尝试。