Java Reference
In-Depth Information
Continued from previous page
This evaluates to 0 with integer division. Some students fix this by changing the
types of all the variables to double . That will solve the immediate problem, but it's
not a good choice from a stylistic point of view. It is best to use the most appropriate
type for data, and the number of questions on the test will definitely be an integer.
You could try to fix this by changing the value 100 to 100.0 :
percent = numRight / totalQuestions * 100.0; // incorrect
but this doesn't help because the division is done first. However, it does work if
you put the 100.0 first:
percent = 100.0 * numRight / totalQuestions;
Now the multiplication is computed before the division, which means that
everything is converted to double .
Sometimes you can fix a problem like this through a clever rearrangement of
the formula, but you don't want to count on cleverness. This is a good place to
use a cast. For example, returning to the original formula, you can cast each of
the int variables to double :
percent = (double) numRight / (double) totalQuestions * 100.0;
You can also take advantage of the fact that once you have cast one of these
two variables to double , the division will be done with doubles. So you could,
for example, cast just the first value to double :
percent = (double) numRight / totalQuestions * 100.0;
2.3 The for Loop
Programming often involves specifying redundant tasks. The for loop helps to avoid
such redundancy by repeatedly executing a sequence of statements over a particular
range of values. Suppose you want to write out the squares of the first five integers.
You could write a program like this:
1 public class WriteSquares {
2 public static void main(String[] args) {
3 System.out.println(1 + " squared = " + (1 * 1));
4 System.out.println(2 + " squared = " + (2 * 2));
5 System.out.println(3 + " squared = " + (3 * 3));
6 System.out.println(4 + " squared = " + (4 * 4));
7 System.out.println(5 + " squared = " + (5 * 5));
8 }
9 }
 
 
Search WWH ::




Custom Search