• 输入一个整数,要求不管输入什么,程序都不会崩溃


    用到异常处理机制的输入成绩保证程序健壮性的代码

    1.编写一个程序,此程序在运行时要求用户输入一个整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

    2.要求程序必须具备足够的健壮性,不管用户输入什么样的内容,都不会崩溃。

    用到了异常处理机制

    import java.util.Scanner;

    /*编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,2015.11.12底云飞

    *程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

    要求程序必须具备足够的健壮性,不管用户输入什 么样的内容,都不会崩溃。

    */

    class Score1{

    int scored;

    private Scanner sc;

    void set(){

    sc=new Scanner(System.in);

    try{

    System.out.println("请输入0到100间的成绩");

    scored=sc.nextInt();//表示语句可能会出现异常

    }

    catch(Exception e){//捕获异常

    System.out.println("输入有误,请重输");

    set();//返回去用这个get方法

    }

    }

    void show()

    {

    if(scored<60&&scored>=0)

    System.out.println("不及格");

    if(scored>=60&&scored<70)

    System.out.println("及格");

    if(scored>=70&&scored<80)

    System.out.println("中");

    if(scored>=80&&scored<90)

    System.out.println("良");

    if(scored>=90&&scored<100)

    System.out.println("优");

    if(scored<0||scored>100)

    {

    System.out.println("输入范围不,请重输");

    set();

    show();//同第一个get()方法一样

    }

    }

    }

    public class Score extends Score1{

    public static void main(String args[]){

    Score1 sc=new Score1();

    sc.set();

    sc.show();

    }

    }

  • 相关阅读:
    java的异常抛出和String类常用方法
    监控工具zabbix
    监控工具nagios
    监控工具cacti
    LB集群
    高可用集群(HA)配置
    vsftp虚拟用户登录配置详解
    Ubuntu中设置静态IP和DNS(转载)
    虚拟机克隆linux系统后需要做的网络设置
    CentOS 6.8编译安装httpd2.2.31+MySQL5.6.31+PHP5.3.27
  • 原文地址:https://www.cnblogs.com/diyunfei/p/4959951.html
Copyright © 2020-2023  润新知