动手动脑之小程序:TryAndCatch

源代码

import java.util.InputMismatchException;
import java.util.Scanner;
public class TryAndCatch {
public void grade(double f)
{
if(f>=0&&f<60){System.out.println("不及格!");}
else if(f>=60&&f<70){System.out.println("及格!");}
else if(f>=70&&f<80){System.out.println("中!");}
else if(f>=80&&f<90){System.out.println("良!");}
else if(f>=90&&f<=100){System.out.println("优!");}
else if(f>100){System.out.println("输入不合法!");}
else if(f<0){System.out.println("输入不合法!");}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner in=new Scanner(System.in);
TryAndCatch t=new TryAndCatch();
int f;

for(;;)
{
System.out.println("请输入分数,判断分数等级:");
try{
f=in.nextInt();
t.grade(f);
}
catch(InputMismatchException e){
//e.printStackTrace(); 
System.out.println("输入不合法!");
}
finally{
System.out.println("如果想重新输入一个分数请按任意键,否则请按q:");
String s=in.next();
if(s.equals("q"))
System.exit(0);
else
continue;
}
in.close();
}
}
}

运行截图

原文地址:https://www.cnblogs.com/love528/p/4963102.html