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

Java代码报错求助:int与String运算/类型不匹配问题修复

问题解答

一、修复当前代码的报错问题

你的两个报错根源是类型不匹配和计算逻辑错误,具体修复步骤如下:

1. 修正类型转换与变量定义

  • 单价(unitPrice)是小数,不能转int,要转成double;折扣(appliedDiscount)同理用double;订单数量(orderQuantity)是整数,转int即可。
  • 折扣前/后总价涉及小数计算,要用double类型存储,不能用int(否则会丢失精度,还会触发类型转换错误)。

2. 修正计算逻辑

原代码中afterDiscount的公式完全错误,正确逻辑应该是:折扣后总价 = 折扣前总价 × (1 - 折扣率),不能直接用1 - ...的减法逻辑。

3. 补全结果输出

原代码只打印了提示文字,没有输出计算后的数值,需要把变量加入输出语句。

修复后的完整代码:

import java.util.Scanner;

public class Asgn1 {
    //comment practice
    /*multi-line comment practice
    * no text fill
     */
    public static void main(String[] args) {

        //user prompted inputs for future calculations
        Scanner in = new Scanner(System.in);
        System.out.println("The following information is required:");
        System.out.println("Enter customer ID: ");
        String customerId = in.nextLine();
        System.out.println("Enter unit price in decimal format (up to two decimals, e.g. 3.5): ");
        double unitPrice = Double.parseDouble(in.nextLine());
        System.out.println("Enter quantity (whole numbers only): ");
        int orderQuantity = Integer.parseInt(in.nextLine());
        System.out.println("Enter product description, (e.g. 'whole wheat bread'): ");
        String productDescription = in.nextLine();
        System.out.println("Enter discount in decimal format (e.g. .05 = 5%): ");
        double appliedDiscount = Double.parseDouble(in.nextLine());

        //confirm order data details and display to user
        System.out.println("Your order data is as follows: ");
        System.out.println("Customer ID: " + customerId);
        System.out.println("Unit Price: " + unitPrice);
        System.out.println("Order Quantity: " + orderQuantity );
        System.out.println("Product Description: " +  productDescription);
        System.out.println("Applied Discount: " + appliedDiscount);

        //calculation formulas based on users input
        double beforeDiscount = unitPrice * orderQuantity;
        double afterDiscount = beforeDiscount * (1 - appliedDiscount);
        
        //totals before and after discount
        System.out.println("Your Order Totals");
        System.out.println("Before Discount: " + beforeDiscount);
        System.out.println("After Discount: " + afterDiscount);

    }
}

二、输入阶段处理VS获取后转换的规范选择

从Java开发规范和健壮性角度,优先在输入阶段处理数值类型,原因如下:

  • 及时校验合法性:用户输入非数字(比如字母、乱码)时,能立刻捕获NumberFormatException,并提示用户重新输入,避免到计算阶段才报错,提升交互体验。
  • 代码更简洁:后续计算无需重复转换,直接使用强类型变量,减少冗余代码。
  • 类型安全:提前确定变量类型,避免后续操作中出现隐式转换错误,让代码逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:15:37