Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write code Game.java : Ensure user to enter an integer in [1, 6] from the keyboa

ID: 3880978 • Letter: W

Question

Write code Game.java:

Ensure user to enter an integer in [1, 6] from the keyboard, that is, an integer from 1 to 6. Note that if a user enters an integer other than 1, 2, 3, 4, 5, 6, your program would force the user to re-enter again.

Let computer generate a random integer in [1, 6]. Print it out.

If the user and computer generate the same integer, print out “a tie”; otherwise, if the user’s input is a multiple of the computer’s number, print out “user wins”; otherwise, if the computer’s number is a multiple of the user’s input, print out “computer wins”; otherwise, print out “undecided”

For example, 6 is a multiple of 2 since 6 can be divided by 2. Said differently, given two integers m and n, integer m is a multiple of n if the remainder of m divided by n is zero.

Explanation / Answer

/*The whole answer is well commented so please copy whole answer to your ide and

* Run it. The class name is Game.java

* Solution Steps:

* I am using Scanner class to read input from user and Random function to generate random number

* I will read user input in infinite while loop and terminate loop only when user enters

* a valid number

* and program will check for winner/tie only after valid input

*

* To check multiple , I am going to use %(module) operator

* a%b gives remainder

* if(a%b==0) then a is multiple of b

* */

//Java Program to play a game with computer

import java.util.*;

public class Game {

public static void main(String[] args) {

//Instantiating Scanner

Scanner sc=new Scanner(System.in);

//variables to store valus

int userInput=0;

int compInput;

boolean flag=true;

//Loop will run till user enters valid input

while(flag)

{

System.out.println("Please enter a number between 1 and 6: ");

userInput=sc.nextInt();

//changing the value of flag when valid input received

if(userInput>=1 && userInput<=6)

{

flag=false;

}

}

//Generating random number

Random random = new Random();

compInput=random.nextInt(6) + 1;

//printing Computer random number

System.out.println("Random Generated Number: "+compInput);

//Lets check for game conditions

//if(a%b==0) means a is divisible of b and a is multiple of b

if(userInput==compInput)

{

System.out.println("a tie");

}

else if(userInput%compInput==0)

{

System.out.println("user wins");

}

else if(compInput%userInput==0)

{

System.out.println("computer wins");

}

else

{

System.out.println("undecided");

}

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote