Java Reference
In-Depth Information
for (int i = 1; i <= length - 1; i++) {
if (value % 2 == 0) {
value = value / 2;
} else {
value = 3 * value + 1;
}
if (value > max) {
max = value;
} else if (value < min) {
min = value;
}
}
System.out.println("max = " + max);
System.out.println("min = " + min);
}
Cumulative Sum with if
Let's now explore how you can use if/else statements to create some interesting
variations on the cumulative sum algorithm. Suppose you want to read a sequence of
numbers and compute the average. This task seems like a straightforward variation of
the cumulative sum code. You can compute the average as the sum divided by the
number of numbers:
double average = sum / totalNumber;
System.out.println("average = " + average);
But there is one minor problem with this code. Suppose that when the program
asks the user how many numbers to process, the user enters 0 . Then the program will
not enter the cumulative sum loop, and your code will try to compute the value of 0
divided by 0 . Java will then print that the average is NaN , a cryptic message that is
short for “Not a Number.” It would be better for the program to print out some other
kind of message which indicates that there aren't any numbers to average. You can
use an if/else statement for this purpose:
if (totalNumber <= 0) {
System.out.println("No numbers to average");
} else {
double average = sum / totalNumber;
System.out.println("average = " + average);
}
Another use of if statements would be to count how many negative numbers the
user enters. You will often want to count how many times something occurs in a program.
 
Search WWH ::




Custom Search