You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java作业:如何将SPA项目费用累加到总cost变量中?

解决SPA菜单费用累加问题

直接给你修正后的完整代码,同时说明关键修改点:

import java.util.Scanner;
public class SpaReception{
  public static void main(String[] args) {
    double cost = 0;
    int treatment = 0;

    final double faceMask = 600.00;
    final double footMassage = 300.00;
    final double fullBodyMassage = 1500.00;

    Scanner input = new Scanner(System.in);  //create scanner for input
    System.out.println("Type in which treatment you've gotten ");
    System.out.println("Face mask: 1");
    System.out.println("Foot massage: 2");
    System.out.println("Full body massage: 3");
    System.out.println("Cancel: -1");
    treatment = input.nextInt();

    switch (treatment) {
      case 1: 
        cost += faceMask; // 累加面膜项目费用
        break;
      case 2:
        cost += footMassage; // 累加足部按摩费用
        break;
      case 3:
        cost += fullBodyMassage; // 累加全身按摩费用
        break;
      case -1:
        System.out.println("Operation cancelled.");
        break;
      default:
        System.out.println("Invalid treatment selection.");
        break;
    }

    System.out.println("The cost is: "+cost);
  }
}

关键修改说明:

  • 修正switch参数笔误:原代码里switch(treatments)是错误写法,改成switch(treatment)才能匹配输入的选项变量
  • 实现费用累加:在对应case分支里使用cost += 常量名的语法,直接把项目费用加到总费用cost上,完全符合使用已有常量的要求,无需新增任何常量
  • 完善分支逻辑:添加case -1处理取消操作,新增default分支处理无效输入,同时移除原代码中多余的case 4(菜单无对应选项)

内容的提问来源于stack exchange,提问作者quasireal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:02:53