我有一个Java程序,旨在接受客户的输入,然后为每个客户运行一个循环。然后用户有3个选择输入:小丑,野生动物园山姆或音乐大篷车。我只是不明白我的if
陈述有什么问题。您会看到,如果用户输入" clowns",则相应的if
语句正常工作,并执行if
语句。但是,如果用户输入" safari sam"或"音乐大篷车",if
语句不执行。
我的问题是:如果执行了第一个if
语句,那么为什么要跳过其他2个语句(在满足条件时不执行)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
答案 0 :(得分:4)
您需要使用nextLine()
代替next()
来阅读用户输入。 nextLine()
会读取整行,但next()
只会读取下一个单词。
答案 1 :(得分:1)
要读取用户在控制台中提供的字符串,必须使用.nextLine() 所以尝试使用这个 -
String service_type = new_scan.nextLine();
这应该将您在控制台中提供的任何内容的值存储到String&#34; service_type&#34;。