我无法在我的个人项目中使用if
和else if
语句。
在询问用户输入时,我的程序似乎在第一行正常工作,但代码中存在问题。我的编译器要求我使用switch方法。
我也遇到过编译器告诉我无法将String
转换为double
的问题,这是我已经使用搜索找到的内容。
我知道这可能有很多要问,但我真的很感谢你的帮助。
/**
* This application executes number of gallons purchased, car wash if the
* customer desires.
* There will be four options, Regular, Premium, Super,
* or None. A car wash is $1.25 if purchased with $10.00 or more. If it is
* anything equal or below $9.99 then the car wash fee is $3.00.
* Regular per gallon is $2.89
* Premium per gallon is $3.09
* Super per gallon is $3.39
*
*
* @author Christian Guerra
*/
package finalflight;
//The line below is preparing the system to ask the user for inputs
import java.util.Scanner;
public class ExxonCarServices {
public static void main(String[] args) {
String gasType;
String carWash;
String gasPrice;
String numGallons;
double gasRegular = 2.89;
double gasPremium = 3.09;
double gasSuper = 3.39;
double gasNone = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Hello which type of gas would you like today? "
+ "Please make the selection Regular, Premium, Super, or None" + " ");
gasType = keyboard.nextLine();
System.out.print("How many gallons would you like?" + " ");
numGallons = keyboard.nextLine();
System.out.print("Would you like to add a professional car wash cleaning today?"
+ " " + "Please select Yes or No" + " ");
carWash = keyboard.nextLine();
if (gasType.equals("Regular")) {
gasRegular = Regular;
} else if (gasType.equals ("Premium")) {
gasPremium = Premium;
} else if (gasType.equals("Super")) {
gasSuper = Super;
} else {
gasNone = 0;
}
if (numGallons * gasPrice <10) {
carWash = 3;
} else {
carWash = 1.25;
}
}
}
答案 0 :(得分:1)
编译器告诉你这段代码是正确的:
if (gasType.equals("Regular")) {
gasRegular = Regular;
} ...
但是从Java 7.0开始也可以使用switch语句编写:
switch (gasType) {
case "Regular":
gasRegular = Regular;
break;
case "Premium":
gasPremium = Premium;
break;
....
}
您遇到的错误&#34;无法将字符串转换为双倍&#34;可能是因为Double.parseDouble(someString)
在String
类型的变量中分配时遗失Double
。
答案 1 :(得分:0)
我怀疑编译器告诉你使用交换机案例,它可能只是建议它(对于多个项目,交换机案例几乎总是更好可读性选项。
要将String
转换为Double
,只需使用Double.parseDouble()
。
在你的情况下,这看起来像这样:
double numGallonsDouble = Double.parseInt(numGallons);