在处理这段代码一段时间并接近尾声后,我遇到了一个意想不到的问题。选项“B”和“C”的 if 和 else 语句在作为用户输入输入时在屏幕上不显示任何内容。我已经尝试了一些事情,但我似乎无法弄清楚。
import java.util.Scanner;
public class Internet_Service_Provider
{
public static void main(String[] args)
{
double hours;
char choice;
Scanner input = new Scanner(System.in);
System.out.println ("Enter the letter of your package: ");
choice = input.nextLine().charAt(0);
System.out.println ("Enter the number of hours used: ");
hours = input.nextDouble();
double chargesa, chargesb, chargesc;
chargesa = 9.95;
chargesb = 13.95;
chargesc = 19.95;
double chargesa2, chargesb2;
chargesa2 = (hours - 10) * 2;
chargesb2 = (hours - 20);
double extrafeesA, extrafeesB;
extrafeesA = chargesa + chargesa2;
extrafeesB = chargesb + chargesb2;
if (choice == 'A')
if (hours <= 10) {
System.out.println ("Your total charges are: " + chargesa);
}
else if (choice == 'A')
if (hours > 10){
System.out.println ("your total charges are: " + extrafeesA);
}
else if (choice == 'B')
if (hours <= 20) {
System.out.println ("Your total charges are: " + chargesb);
}
else if (choice == 'B')
if (hours > 20){
System.out.println ("Your total charges are: " + extrafeesB);
}
else if (choice == 'C'){
System.out.println ("Your total charges are: " + chargesc);
}
}
}
当用户输入“A”然后输入小时数时,程序运行完美并给了我想要的输出。如果输入“B”或“C”,然后输入小时,则屏幕上没有输出。这是什么原因造成的?
-编辑-我在检查响应之前弄乱了代码,发现如果删除 else 并创建此代码:
if (choice == 'A')
if (hours <= 10) {
System.out.println ("Your total charges are: " + chargesa);
}
if (choice == 'A')
if (hours > 10){
System.out.println ("your total charges are: " + extrafeesA);
}
if (choice == 'B')
if (hours <= 20) {
System.out.println ("Your total charges are: " + chargesb);
}
if (choice == 'B')
if (hours > 20){
System.out.println ("Your total charges are: " + extrafeesB);
}
if (choice == 'C'){
System.out.println ("Your total charges are: " + chargesc);}
...程序运行正常。我猜其他语句是不必要的并导致了问题。