课堂测试---程序的Robust性

让用户输入考试成绩,输入格式正确(输入0到100的整数)才会成功输入,并显示成绩评级。

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		while(true) {
			int x=input();
			show(x);
		}
	}
	static void show(int x) {
		if(x>=90) System.out.println("优");
		else if(x>=80) System.out.println("良");
		else if(x>=70) System.out.println("中");
		else if(x>=60) System.out.println("及格");
		else System.out.println("不及格");
	}
	static int input() {
		Scanner sc=new Scanner(System.in);
		int x=0;
		while(true) {
			System.out.println("输入考试成绩:");
			String s=sc.next();
			boolean f=true;
			if(s.length()>3) f=false;
			for(int i=0;i<s.length();i++) {
				if(s.charAt(i)<'0'||s.charAt(i)>'9'||i==0&&s.charAt(i)=='0'&&s.length()!=1) {
					f=false;
					break;
				}
			}
			if(f!=false) {
				x=Integer.parseInt(s);
				if(x<0||x>100) f=false;
			}
			if(f==false) {
				System.out.println("格式错误");
			}
			else return x;
		}
	}
}

ps:格式不正确但能输入成功者,送人民币6.66元。有意者加QQ:2953488214

posted @ 2021-10-29 14:50  zhuangzhongxu  阅读(82)  评论(0)    收藏  举报