CS61B Lab2 Debugging

实验2主要内容

  • 教你使用IDE中调试步骤,学会设置断点调试代码
  • 学以只用,学会设置断点之后,就开始改代码错误了

本节需要学什么?

Java配置Configration

当你导入一个项目模块时,需要添加修改configration的以下内容。
image.png

Junit的导入

有时候运行的时候会出现“junit不存在等情况”
image.png
这时候就要导入junit包,调用里面的函数:
在这里导入:
image.png
image.png

assertEquals的应用

这个函数的作用就是评测你输出的代码是否与预期测试一致

开始改代码

Arithmetic

    public static int sum(int a, int b) {
        return a + b;
    }
    //原来是乘法改为加法即可

DeBugExercise1

    public static int divideThenRound(int top, int bottom) {
        float quotient = (float) top / bottom;
        int result = Math.round(quotient);
        return result;
    }

变为浮点数

DeBugExercise2

    public static int max(int a, int b) {
        return a>b?a:b;
    }

改写max函数,原来得到的是a和b当中比较小的值。

InitListExericise

    public static void addConstant(IntList lst, int c) {
        IntList head = lst;
        while (head!= null) {
            head.first += c;
            head = head.rest;
        }
    }

原来是head->rest改为head

    public static boolean firstDigitEqualsLastDigit(int x) {
        int lastDigit = x % 10;
        while (x >= 10) {
            x = x / 10;
        }
        int firstDigit = x % 10;
        return firstDigit == lastDigit;
    }

x>10改为x>=10
最后一个

    public static boolean squarePrimes(IntList lst) {
        // Base Case: we have reached the end of the list
        if (lst == null) {
            return false;
        }

        boolean currElemIsPrime = Primes.isPrime(lst.first);

        if (currElemIsPrime) {
            lst.first *= lst.first;
        }

        //return currElemIsPrime || squarePrimes(lst.rest);
        return squarePrimes(lst.rest)||currElemIsPrime;
    }

这个比较巧妙,原来是currElemIsPrime || squarePrimes(lst.rest),这里如果currElemlsPrime如果为真值,后面就不进行递归了,因此需要交换位置。
提交:
image.png

评测

image.png
全对

posted @ 2024-04-26 15:07  夏muer  阅读(378)  评论(0)    收藏  举报