java流程控制(day04)

java流程控制

1.用户交互

import java.util.Scanner

Scanner sc=new Scanner(System.in);

1773130767725

判断是否是对应的类型用hasNextxxx类型,如果不判断,会抛出异常,判断是不是符合的输入要求。

package com.baidu.salarycalculator; // 包名同步修正拼写

import java.util.Scanner;

/**
 * 薪资计算器
 * 功能:根据基本工资、绩效奖金、出勤天数计算实际薪资
 */
public class SalaryCalculator { // 修正类名拼写

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int baseSalary, attendanceDays, tempDays;
        double performanceBonus, salary;

        // 1. 读取基本工资(整数+正数校验)
        System.out.println("请输入你的基本工资(正整数,单位:元):");
        while (true) {
            if (!sc.hasNextInt()) {
                String wrongInput = sc.nextLine();
                System.out.println("输入错误:你输入的「" + wrongInput + "」不是整数,请重新输入!");
            } else {
                baseSalary = sc.nextInt();
                sc.nextLine(); // 消费换行符,规避Scanner坑
                if (baseSalary > 0) {
                    break; // 基本工资为正,退出校验
                } else {
                    System.out.println("输入错误:基本工资不能为负数/0,请重新输入!");
                }
            }
        }

        // 2. 读取绩效奖金(小数+非负校验)
        System.out.println("请输入你的绩效奖金(非负数,单位:元):");
        while (true) {
            if (!sc.hasNextDouble()) {
                String wrongInput = sc.nextLine();
                System.out.println("输入错误:你输入的「" + wrongInput + "」不是数字,请重新输入!");
            } else {
                performanceBonus = sc.nextDouble();
                sc.nextLine(); // 消费换行符
                if (performanceBonus >= 0) {
                    break; // 绩效奖金非负,退出校验
                } else {
                    System.out.println("输入错误:绩效奖金不能为负数,请重新输入!");
                }
            }
        }

        // 3. 读取出勤天数(整数+0-22范围校验)
        System.out.println("请输入你的出勤天数(0-22天,每月满勤22天):");
        while (true) {
            if (!sc.hasNextInt()) {
                String wrongInput = sc.nextLine();
                System.out.println("输入错误:你输入的「" + wrongInput + "」不是整数,请重新输入!");
            } else {
                tempDays = sc.nextInt();
                if (tempDays >= 0 && tempDays <= 22) {
                    attendanceDays = tempDays;
                    break;
                } else {
                    System.out.println("输入错误:出勤天数需在0-22之间,请重新输入!");
                }
            }
        }

        // 4. 计算实际薪资(规避整数除法)
        salary = baseSalary * (attendanceDays / 22.0) + performanceBonus;

        // 5. 格式化输出(优化格式,更友好)
        System.out.printf("\n你的本月实际薪资为:%.2f 元\n", salary);

        // 6. 关闭Scanner资源
        sc.close();
    }
}

同时每次判断完用完之后需用sc.nextLine()规避空格符。

用完之后需要关闭sc.close.

posted @ 2026-03-13 15:17  蓝蓝1229  阅读(0)  评论(0)    收藏  举报