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

Java字符变量比较问题:程序编译失败,请求排查原因

Hey there! Let's break down why your Java code won't compile and fix a couple of logical quirks too:

1. The immediate compile error: Scanner has no nextChar() method

Java's Scanner class doesn't include a nextChar() method—this is the main reason your code fails to build. To grab a single character from user input, you'll need to first get the input as a string, then pull the first character using charAt(0):

char cate = sc.next().charAt(0);

2. Case mismatch issue

Your prompt asks users to enter A or B, but your condition checks for cate == 'a' (lowercase). If someone enters uppercase A, the discount won't apply. Fix this by normalizing the input to lowercase (or uppercase) before checking:

if (Character.toLowerCase(cate) == 'a')

3. Minor readability tweak (not a compile error, but helps clarity)

The line System.out.println("type total to pay a" + cate + "."); is a bit awkward. Rewording it to something like this makes the prompt clearer for users:

System.out.println("Type total to pay for category " + cate + ":");

Fixed full code

Here's the revised code with all these changes (plus a couple of variable name tweaks for better readability):

import java.util.Scanner;

public class PaymentCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double discountRate = 0.05;
        System.out.println("Category type *A* or *B*");
        char cate = sc.next().charAt(0);
        System.out.println("Type total to pay for category " + cate + ":");
        double totalAmount = sc.nextDouble();
        
        if (Character.toLowerCase(cate) == 'a') {
            totalAmount *= (1 - discountRate); // Simplified discount calculation
        }
        
        System.out.println("Amount to pay is " + totalAmount + " pesos.");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:04:42