【问题标题】:How to to use if and else statements properly?如何正确使用 if 和 else 语句?
【发布时间】:2014-10-04 21:44:26
【问题描述】:

在我的个人项目中使用 ifelse 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


【解决方案1】:

编译器告诉你这段代码是正确的:

if (gasType.equals("Regular")) { 
  gasRegular = Regular;
} ...

但从 Java 7.0 开始也可以使用 switch 语句编写:

switch (gasType) {
case "Regular":
  gasRegular = Regular;
  break;
case "Premium":
  gasPremium = Premium;
  break;
  ....
}

您得到的关于“无法将字符串转换为双精度”的错误可能是由于在将 String 分配给 Double 类型的变量时缺少 Double.parseDouble(someString)

【讨论】:

    【解决方案2】:

    我怀疑编译器是否告诉你使用 switch-case,它可能只是建议它(对于不止几个项目,为了可读性,switch-case 几乎总是更好的选择)。

    要将String 转换为Double,只需使用Double.parseDouble()

    在你的情况下,这看起来像这样:

    double numGallonsDouble = Double.parseInt(numGallons);
    

    【讨论】:

      最近更新 更多