简体   繁体   English

if else 语句返回 else 值,即使它们应该返回 if 值?

[英]if else statements returning else value even when they should return if value?

Thanks for any help in advance.提前感谢您的任何帮助。 Please note I am a beginner.请注意,我是初学者。 Below is the code.下面是代码。 It only prints the else statements value being "Thank you for buying with us" even when the if statements value should be getting printed to the console instead?它只打印 else 语句的值是“感谢您与我们一起购买”,即使 if 语句值应该打印到控制台?

class Main {
  
String type;
double price;
boolean order;

public Main(String whatPizza, double costOfPizza, boolean yourOrder){
  if (price > 10.00){
    System.out.println("Thank you for spending over 10 pounds with us!");
  } else {
    System.out.println("Thank you for buying with us!");
  }

  type = whatPizza;
  price = costOfPizza;
  order = yourOrder;
}


  public static void main(String[] args) {
    //empty for now
  Main personA = new Main("Pepperoni", 11.00, true);
  Main personB = new Main("Cheese", 9.00, true);

    }
  }

The order of your code is not right.你的代码顺序不对。 You don't have any value assigned to price when you run the if-statement.运行 if 语句时,您没有为 price 分配任何值。 Right now the double variable price is always empty, so it's never bigger than 10.00, thus being false and returning the else.现在双变量价格始终为空,因此它永远不会大于 10.00,因此为假并返回 else。 This should do the trick:这应该可以解决问题:

class Main {
  
String type;
double price;
boolean order;

public Main(String whatPizza, double costOfPizza, boolean yourOrder){

  type = whatPizza;
  price = costOfPizza;
  order = yourOrder

  if (price > 10.00){
    System.out.println("Thank you for spending over 10 pounds with us!");
  } else {
    System.out.println("Thank you for buying with us!");
  }

  ;
}


  public static void main(String[] args) {
    //empty for now
  Main personA = new Main("Pepperoni", 11.00, true);
  Main personB = new Main("Cheese", 9.00, true);

    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM