I am trying to make a program which will take a random guess from a range of numbers and checks whether it matches with the given number.
It will run 10times, it the program guesses the correct answer then it will terminate but if not then it will terminate with rejection.
at GuessingTest.main(GuessingTest.java:33)
**current directly** ; /usr/bin/env /Li
brary/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home/bin/java @/var/folders/zl/r96mn6p116125gw39hst2gp40000gn/T/cp_2tq0yp3psptn6qjx3o6su
w328.argfile GuessingTest
Exception in thread "main" java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:87)
at org.junit.Assert.assertTrue(Assert.java:42)
at org.junit.Assert.assertTrue(Assert.java:53)
at GuessingTest.guess(GuessingTest.java:30)
at GuessingTest.main(GuessingTest.java:35)
Below is my code Guessing.java
public class Guessing {
// Your local variables here
private int low = 0;
private int high = 1000;
int randomNum;
/**
* Implement how your algorithm should make a guess here
*/
public int guess() {
randomNum = (int) ((Math.random() * (low - high)) + low);
return randomNum;
}
/**
* Implement how your algorithm should update its guess here
*/
public void update(int answer) {
if (answer == 1) {
low = randomNum;
} else if (answer == -1) {
high = randomNum;
}
}
}
GuessingTest.java
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.*;
public class GuessingTest {
@Test
public void guess() {
Random r = new Random();
int hiddenNumber = r.nextInt(1001);
Guessing g = new Guessing();
int remainingGuesses = 10;
while (remainingGuesses >= 0) {
int guess = g.guess();
if (guess == hiddenNumber) {
break;
} else if(guess > hiddenNumber) {
g.update(1);
remainingGuesses--;
} else {
g.update(-1);
remainingGuesses--;
}
}
assertTrue(remainingGuesses >= 0);
}
public static void main(String[] args) {
GuessingTest test = new GuessingTest();
test.guess();
}
}