In: Computer Science
I have to use a sentinel while loop to complete the following task in a java program, I want to see how this is executed so I can better understand how the sentinel while loop works. Thank you!
Convert Lab 10 from a counter controlled WHILE loop to a sentinel WHILE loop. Do the following:
Include the following:
JAVA CODE
import java.util.Scanner; // import Scanner class
// implement driver class GradeCheck
class GradeCheck
{
public static void main(String [] args)
{
int grade,cnt=0,sum=0; // declare integer variables
grade,cnt,sum
float average; // declare float variable average
Scanner scr=new Scanner(System.in); // create Scanner class object
"scr"
while(true) // create infinite while loop
{
System.out.print("Enter a grade or
a -1 to quit: ");
grade=scr.nextInt(); // read
grades
if(grade==-1) // check
grade=-1
{
// print this
message
System.out.println("User is done entering grades...");
break; //
terminate while loop
}
else{ // else,
sum+=grade; //
compute sum of grades
cnt++; //
increment counter
}
} // end of while loop
if(cnt!=0) // check counter cnt not =0 then,
{
average=sum/(float)cnt; // compute
average
System.out.println("Average of the
grades: "+average); // print average
}
} // main end
} // class end
OUTPUTS:
D:\>javac GradeCheck.java
D:\>java GradeCheck
Enter a grade or a -1 to quit: 2
Enter a grade or a -1 to quit: 3
Enter a grade or a -1 to quit: 4
Enter a grade or a -1 to quit: 4
Enter a grade or a -1 to quit: -1
User is done entering grades...
Average of the grades: 3.25
D:\>java GradeCheck
Enter a grade or a -1 to quit: -1
User is done entering grades...
PROGRAM SCREENSHOTS