[英]Exception in thread "main" java.lang.AssertionError. What shall I do?
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.它会运行 10 次,如果程序猜对了正确答案,那么它就会终止,但如果没有,它就会因拒绝而终止。
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下面是我的代码 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 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();
}
}
The exception you're getting is a result of failing the guess()
test.您得到的异常是guess()
测试失败的结果。
assertTrue(remainingGuesses >= 0);
In other words, you're expecting the hiddenNumber
to be found within 11 steps (0..10), but it's not.换句话说,您希望在 11 步 (0..10) 内找到hiddenNumber
,但事实并非如此。 And there's no reason for it to be.没有理由这样做。 Your code returns negative numbers.您的代码返回负数。
Also it wouldn't work even if it was returning positive numbers, since you could easily guess 0, 1, 2... up to 10, ending with 10 as low
and 1000 as high
.即使它返回正数它也不会工作,因为您可以轻松猜测 0、1、2... 最多 10,以 10 as low
和 1000 as high
结尾。
Also -- how to get random numbers within a specific range: https://stackoverflow.com/a/5887745/684296另外——如何获取特定范围内的随机数: https://stackoverflow.com/a/5887745/684296
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.