# Declaring floating point number depending on an if statement

• August 10th, 2011, 04:13 PM
Keys767
Declaring floating point number depending on an if statement
Hello,
I'm trying some basic Java exercises, but I'm stuck on one of them.

My code is:

Code :

```import javax.swing.JOptionPane; public class PrintingDiscount   { public static void main(String[] args)   { String numberOfFlyersInput = JOptionPane.showInputDialog("How many flyers?"); String numberOfPostersInput = JOptionPane.showInputDialog("How many posters?");   int numberOfFlyers = Integer.parseInt(numberOfFlyersInput); int numberOfPosters = Integer.parseInt(numberOfPostersInput);   double flyerTotal = 0; double posterTotal = 0; double grandTotal = 0; double costOfPoster = 2.00;   /* if (numberOfFlyers >= 500) { double costOfFlyer = 0.005; } else { double costOfFlyer = 0.01; } */   flyerTotal = (costOfFlyer * numberOfFlyers); posterTotal = (costOfPoster * numberOfPosters);   grandTotal = (flyerTotal + posterTotal);   JOptionPane.showMessageDialog(null, "Your flyers will cost £" + flyerTotal + "\nYour posters will cost £" + posterTotal + "\nIn total, this will cost £" + grandTotal); } }```

The part commented out is my problem. I basically want to declare costOfFlyer as 0.01, unless the number entered by the user (numberOfFlyers) is 500 or more, in which case I want it to be 0.005.

So, I've roughly coded what I thought might achieve this, but it is obviously incorrect since the compiler now cant find the variable costOfFlyer.

Any tips would be appreciated. Thanks :)
• August 10th, 2011, 05:06 PM
Norm
Re: Declaring floating point number depending on an if statement
You have defined that variable inside of a pair of {}s. The {}s define the scope or definitional visibility of the variable. The variable is not defined outside of the {}s.
You need to move the definition of the variable to the same level of enclosing {}s that you want other code to be able to see it.
You should put its definition with the other doubles you are defining.
• August 11th, 2011, 01:50 PM
Keys767
Re: Declaring floating point number depending on an if statement
Moved some stuff around and got it to work (shouldn't have been using 'double' inside the if statement X_X). Thanks for the push in the right direction. (*)