Din*_*les 2 java if-statement statements
在处理这段代码一段时间之后,我几乎遇到了一个意外的问题。当将选项“ 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当用户键入“ A”,然后键入小时数时,程序将完美运行,并为我提供所需的输出。如果输入“ B”或“ C”,然后输入小时数,则屏幕上没有输出。是什么原因造成的?
-EDIT-在检查响应之前弄乱了代码,发现如果删除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);}
Run Code Online (Sandbox Code Playgroud)
...程序正常运行。我猜想else语句是不必要的,并引起了问题。
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);}
}
}
Run Code Online (Sandbox Code Playgroud)
仅添加一些适当的表即可表明,除了“ A”之外,您实际上没有涵盖其他任何情况。列表使代码看起来更清晰,因此更容易发现错误。您需要正确使用括号,因为现在您仅检查choice =='A'。如果没有,则您的代码不会执行任何操作。