import java.util.Random;
import java.util.Scanner;
/**
* Match the user's number and CPU's random number.
*
* @author Valerie Chu
* @version 10/31/2018
*/
public class Loop
{
public static void main(String[] args)
{
Random generator = new Random();
Scanner input = new Scanner(System.in);
int CPUnum = generator.nextInt(10);
System.out.println("Guess a number between 0 to 9.");
int USERnum = input.nextInt(); //You must initialize the condition before loop.
while(USERnum != CPUnum) //while condition is true, do the jobs until it is false, the loop ends.
{
System.out.println("Sorry, you did not get it. Try it again!");
USERnum = input.nextInt(); //You must update the condition before go back to repeat the process.
} //Otherwise, it will become an infinity loop.
System.out.println("Congratuation! You got it!");
}
}
Find the output of the following program segments.
| int x = 10; if(x > 5) { x--; System.out.println(x); } System.out.println("Have a nice day."); |
int x = 3; if(x > 5) { x--; System.out.println(x); } System.out.println("Have a nice day."); |
int x = 10; while(x > 5) { x--; System.out.println(x); } System.out.println("Have a nice day."); |
import java.util.Random;
import java.util.Scanner;
/**
* Match the user's number and CPU's random number.
*
* @author Valerie Chu
* @version 11/5/2018
*/
public class Loop
{
public static void main(String[] args)
{
Random generator = new Random();
Scanner input = new Scanner(System.in);
int CPUnum = generator.nextInt(10);
int USERnum;
do
{
System.out.println("Guess a number between 0 to 9.");
USERnum = input.nextInt();
} while(USERnum != CPUnum); //Check the condition at the end of loop.
System.out.println("Congratuation! You got it!");
}
}