线程“main”java.lang.AssertionError出现异常,怎么办?

xpcnnkqh  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(329)

我正在试着做一个程序,它将从一系列数字中随机猜测,并检查它是否与给定的数字匹配。
它将运行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)

下面是我的代码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();
    }
}
wgx48brx

wgx48brx1#

您得到的异常是guess()测试失败的结果。

assertTrue(remainingGuesses >= 0);

换句话说,您希望在11步(0..10)内找到hiddenNumber,但事实并非如此,而且没有理由这样做,代码返回负数。
而且,即使它返回的是正数,它也不会工作,因为你可以很容易地猜出0、1、2 ......直到10,以10结尾的low和1000结尾的high

相关问题