A variable is a letter (or name)
that represents a value. The number 576.50 above is the income
received from selling baked goods. We could use the letter X
to represent this number.
But the letter X isn't really the clearest choice - we could use I
or INC to represent INCOME =
576.50.
Now rather than writing 576.50 over and over again, we could just write INC,
or just I .
This has several advantages:
Here is a better version of the program, written using variables.
double i = 576.50;
double s = 87.50;
double c = 55.95;
double o = 92.00;
double profit = i-(s+c+o);
System.out.println("Profit = " + profit);
System.out.println("Brazil = " + 0.6 * profit);
System.out.println("Thailand = " + 0.3 * profit);
System.out.println("Parents = " + 0.1 * profit);
This might appear more complex, due to words like "double", and because it's
actually longer.Consistency is also
helpful. If you are going to use whole words for variables - e.g.
profit -
then do that all the time.
"double" is a variable
type. This forces the numbers stored in the variables to be
treated as decimals
rather than integers. As a result, you can write the following and
get a correct answer:
double money = 700;
double people = 8 ;
double share = money / people;
System.out.println("Each person gets " + share + " Euros"); // ==> 87.50
Since all the variables are double
types, the division will be done using decimals and give a correct answer.
It doesn't matter that there are no decimals in 700 or 8. The word float
FORCES these to be treated as decimals.
READ each program below. PREDICT what you think it will
print. Then RUN it and check your answer.
double age = 15; |
double x = 3; |
double price = 7.50; |
double money = 123; |
Each of the following programs contains errors.
Fix the errors and make each program run correctly.
price = 14.95; |
double euros = 150; |
double hours = 8; |
double radius = 7; |