Do...While Demo Fragments

// To print the message HAPPY BIRTHDAY 10 times
int counter = 0;

do
{
     System.out.println( "HAPPY BIRTHDAY! ");
     counter++;
}
while (counter <10);


divider

// To add a total, count, and average grades:
Scanner reply=new Scanner(System.in);
double total = 0;       
// be sure to initialize variables to zero to avoid
int counter = 0;         
// allowing the computer to use it's "garbage".
double average = 0;
int grade;                  
// Why is this variable not set equal to zero? It is filled by user.

do
{
     System.out.println("Enter the grade scored.\n Enter -999 to quit. ");    
     grade=reply.nextInt();;

     if (grade != -999)              
// separating sections of the program 
     {                                          
// by inserting an empty line helps organize
             total += grade;          
// your thinking and allows for easy reading.
             counter++;
      }

}
while (grade != -999);

average = total / counter;

System.out.println("The average of your " + counter + " grades is "+ average +".");
reply.close();

 

Note: If you run this program fragment and enter -999 as your first grade, you will get :
The average of your 0 grades is NaN.

NaN stands for "not a number".
If the counter stays at 0, the average has a division by zero problem, which creates a situation that is "not a number".
For now, you can think of "Division by Zero" error and NaN as basically the same idea. The difference between the two is connected to floating point values and whether "zero" is really 0 and/or 0.0.

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com