I\'m in java one and need help with this code. please follow the directions give
ID: 3684122 • Letter: I
Question
I'm in java one and need help with this code. please follow the directions given and test your program to make sure it works as it is required. I will apreciate your help. thank you.please use the given code. make sure that your program doesn't gives an infinity loop.
Programming Concepts
1. Random Number Generation
Exercise Location
For this exercise, you will copy a program from my directory into yours. It doesn't matter what directory this exercise is located in. You will need to copy this command and paste it into Loki:please use the given code
cp ~lkoperski/1404_Lab/Exercises/Exercise10.java .
Exercise Description
^ You will create a game that has the user guess a number between 1 and 10.
^ Generate a random number that the user will attempt to guess.
^ If the user guesses a number that is lower than the answer, print a message that says that.
^ If the user guesses a number that is higher than the answer, print a message that says that.
^ If the user guesses a number that is equal to the answer, print a message that says that.
user@loki:~$ java Exercise10
I am thinking of a number between 1 and 10!
Enter a guess: 5
Too low!
Enter a guess: 8
Too high!
Enter a guess: 6
Too low!
Enter a guess: 7
You guessed it!
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Scanner;
import java.util.Random;
class Exercise10
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
Random r = new Random();
int START = 1;
int END = 10;
System.out.println("I am thinking of a number between 1 and 10!");
System.out.println("Enter a guess");
int guess = in.nextInt();
int answer = showRandomInteger(START, END, r);
if(guess > answer ){
log("Too high!");
}
else if(guess < answer )
{
log("Too low!");
}
else
{
log("You guessed it!");
}
}
private static int showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
return randomNumber;
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.