In: Computer Science
I am trying to figure out how to properly execute a while loop and a do/while loop in the same program using java. I am stuck at just writing the while loop. I made a condition but I can't figure out how to get it to loop if the condition is true?? Also I have to write a do/while loop in the same program.
here are the details:
Here is what I have written in JAVA so far:
import java.util.Scanner;
public class whileloopanddowhile //BEGIN Class Definition (must be
same as file name)
{
public static void main (String[] args) //BEGIN Main Method
{
//Declare variables
int number;
//List all Class Objects here
Scanner scan = new Scanner(System.in);
//Executable Statement Section, user input
System.out.println ("Enter a grade from 0 to 100 ");
number = scan.nextInt();
//This is where the code goes
while (number < 0 && number > 100 )
{
System.out.println ("ERROR! Must enter a grade between 0 and
100");
}
System.out.println ("You have enetered a valid grade");
}//END main method
}
Thank you for any help and clarification!
import java.util.Scanner;
public class Whileloopanddowhile {
public static void main(String[] args) //BEGIN Main Method
{
//Declare variables
int number;
//List all Class Objects here
Scanner scan = new Scanner(System.in);
//Executable Statement Section, user input
System.out.println("Enter a grade from 0 to 100 ");
number = scan.nextInt();
//This is where the code goes
while (number < 0 || number > 100) {
// Incorrect user input
System.out.println("ERROR! Must enter a grade between 0 and 100");
// Get input from user again
System.out.println("Enter a grade from 0 to 100 ");
number = scan.nextInt();
}
System.out.println("You have entered a valid grade");
// do while loop
do
{
// Check if the grade is invalid
if(number < 0 || number > 100)
System.out.println("ERROR! Must enter a grade between 0 and 100");
// Get input from user
System.out.println("Enter a grade from 0 to 100 ");
number = scan.nextInt();
}
while(number < 0 || number > 100);
System.out.println("You have entered a valid grade");
}//END main method
}
*************************************OUTPUT***************************************************
Enter a grade from 0 to 100
-36
ERROR! Must enter a grade between 0 and 100
Enter a grade from 0 to 100
150
ERROR! Must enter a grade between 0 and 100
Enter a grade from 0 to 100
35
You have entered a valid grade
Enter a grade from 0 to 100
-12
ERROR! Must enter a grade between 0 and 100
Enter a grade from 0 to 100
150
ERROR! Must enter a grade between 0 and 100
Enter a grade from 0 to 100
25
You have entered a valid grade