Java Reference
In-Depth Information
LISTING 5.8
continued
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of games won (0 to "
+ NUM_GAMES + "): ");
won = scan.nextInt();
while (won < 0 || won > NUM_GAMES)
{
System.out.print ("Invalid input. Please reenter: ");
won = scan.nextInt();
}
ratio = ( double )won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println ();
System.out.println ("Winning percentage: " + fmt.format(ratio));
}
}
OUTPUT
Enter the number of games won (0 to 12): -5
Invalid input. Please reenter: 13
Invalid input. Please reenter: 7
Winning percentage: 58%
We generally want our programs to be robust, which means that they handle
potential problems as elegantly as possible. Validating input data and avoiding
errors such as dividing by zero are situations that we should consciously address
when designing a program. Loops and conditionals help us recognize and deal
with such situations.
Infinite Loops
It is the programmer's responsibility to ensure that the condition of a loop will
eventually become false. If it doesn't, the loop body will execute forever, or at
least until the program is interrupted. This situation, referred to as an infinite
loop, is a common mistake.
 
Search WWH ::




Custom Search