java问题

2025-02-27 15:10:02
推荐回答(1个)
回答1:

不知道这个合不合适

package com.kidd.baiduzhidao;

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int i = 0;

        boolean next = false;
        try {
            i = getNumber(scanner);
            next = true;
        } catch (Exception e) {
            System.out.println("您输入的不是1~3的数字,抛出了异常.");
            e.printStackTrace();
        }

        if (next) {
            switch (i) {
            case 1: {
                System.out.println("您输入的数字是" + i + ",代表的课程是语文.");
                break;
            }
            case 2: {
                System.out.println("您输入的数字是" + i + ",代表的课程是数学.");
                break;
            }
            case 3: {
                System.out.println("您输入的数字是" + i + ",代表的课程是英语.");
                break;
            }
            default:
                break;
            }
        }

        System.out.println("欢迎提出建议");

    }

    public static int getNumber(Scanner scanner) throws Exception {
        boolean next = false;

        int i = 0;

        System.out.print("输入1~3之间任一个数字:");

        while (!next) {
            try {
                i = Integer.parseInt(scanner.next());
                next = true;
            } catch (NumberFormatException e) {
                System.out.println("格式不正确,仅能输入数字.");
            }
        }

        if (i < 1 || i > 3) {
            throw new Exception();
        }

        return i;
    }
}