In: Computer Science
Exercise 1 JAVA LANGUAGE
Code:
//as we are using Scanner and random classes we have to
//import this package
import java.util.*;
//class name is Game,So the name of the file should be
Game.java
class Game{
public static void main(String[] args) {
//creating instances for random and
scanner
Random rand = new Random();
Scanner s = new
Scanner(System.in);
//variables declared
int number,guess;
//the generated random number is
stored in variable number
number= rand.nextInt(100);
System.out.println("Guess the
number:");
//an infinite loop which only
breaks when
//user guesses the number
while(true){
//try
block
try{
//taking user input
guess=s.nextInt();
if(guess<number){
System.out.println("The
number you entered is lower than the generated number, Enter
again");
}
else if(guess>number){
System.out.println("The
number you entered is Higher than the generated number, Enter
again");
}
//if the user guesses the number correctly, the
loop breaks
else{
System.out.println("Yay, You
guessed the number correctly,The number is "+number);
break;
}
//exception is handled here
}catch(InputMismatchException e){
System.out.println(e);
//asking the user to input again
System.out.println("You didnt entered an
Integer,Enter again: ");
//for storing the new line character
s.nextLine();
};
}
}
}
Output:
Code Screenshot:
Code Snippet:
//as we are using Scanner and random classes we have to
//import this package
import java.util.*;
//class name is Game,So the name of the file should be Game.java
class Game{
public static void main(String[] args) {
//creating instances for random and scanner
Random rand = new Random();
Scanner s = new Scanner(System.in);
//variables declared
int number,guess;
//the generated random number is stored in variable number
number= rand.nextInt(100);
System.out.println("Guess the number:");
//an infinite loop which only breaks when
//user guesses the number
while(true){
//try block
try{
//taking user input
guess=s.nextInt();
if(guess<number){
System.out.println("The number you entered is lower than the generated number, Enter again");
}
else if(guess>number){
System.out.println("The number you entered is Higher than the generated number, Enter again");
}
//if the user guesses the number correctly, the loop breaks
else{
System.out.println("Yay, You guessed the number correctly,The number is "+number);
break;
}
//exception is handled here
}catch(InputMismatchException e){
System.out.println(e);
//asking the user to input again
System.out.println("You didnt entered an Integer,Enter again: ");
//for storing the new line character
s.nextLine();
};
}
}
}