1

So basically, I get the message that the variable discountPrice might not have been initialized, and I know that to fix that I have change it to double discountPrice = 0, but I dont know "WHY"! Can someone exlain to me why I need to do that for the discountPrice variable but not the other variables?

class Revenue{
  public static void main(String[]args){

    Scanner console = new Scanner(System.in);

    double revenue, price, quantity, discountPrice;

    //Appearently should have double discountPrice = 0 'here'.

    System.out.print ("Enter product price ");
    price = console.nextDouble();

    System.out.print ("Enter quantity ");
    quantity = console.nextDouble();

    revenue = price * quantity;

    if (revenue > 5000){
      discountPrice = revenue * 0.10;
      revenue = revenue - discountPrice;
    }

    System.out.print("Discount Price is " + discountPrice);
    System.out.print("\nNet revenue is " + revenue);
  }
}
djharten
  • 374
  • 1
  • 12
Zerenity
  • 107
  • 6

1 Answers1

1

In your program, you create 4 variables: revenue, price, quantity, and discountPrice. If you take a look you say "Okay price is this input, quantity is this input, and revenue is those first two inputs multiplied". This is done no matter what. After that, however, is an if statement, or what you can refer to as a conditional statement. What that means is something will happen IF a condition is met - in this case if revenue is > 5000.

Since that conditional statement is not guaranteed to be true, and we may not ever get to it, then your IDE will typically tell you that the variable, in this case discountPrice, may not have been initialized.

Another way to put it is that what you are doing here: double revenue, price, quantity, discountPrice; is declaring variables. If you don't assign them to anything, then they have not been initialized. There is a good and succinct explanation of declaring vs. initializing vs. assigning here.

I hope that helps :)

djharten
  • 374
  • 1
  • 12
  • 1
    yeah got it, basically I have to manually allocate value to the variables (for both instance or class variables right). – Zerenity Feb 25 '20 at 15:55
  • 1
    I noted down the keywords, declaring and assigning. Two very important concepts which I will take with me! – Zerenity Feb 25 '20 at 16:00