TransWikia.com

if else statements returning else value even when they should return if value?

Stack Overflow Asked by benstackoverflow on January 5, 2021

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?

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);

    }
  }

One Answer

The order of your code is not right. You don't have any value assigned to price when you run the if-statement. Right now the double variable price is always empty, so it's never bigger than 10.00, thus being false and returning the 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);

    }
  }

Correct answer by JJuless on January 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP