【发布时间】:2014-10-04 21:44:26
【问题描述】:
在我的个人项目中使用 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;
}
}
}
【问题讨论】:
-
请在clear and concise, minimal example 上发布您遇到的问题。此外,请发布您收到的确切错误。我从来没有听说过编译器会告诉你使用哪些结构。
-
您使用 if...then...else 没问题。问题是您将gasRegular定义为双精度,但随后您尝试设置gasRegular = Regular,我假设它是一些字符串常量(您没有包含定义“Regular”的代码部分,“ Premium”和“Super”,除非我错过了。向我们展示设置这些值的代码。
标签: java string sorting netbeans