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

