每日一练101——Java我该如何比较数字(8kyu)

2018-09-20  本文已影响0人  砾桫_Yvan

题目

什么比比较整数更容易?但是,给定的代码片段无法识别某些特殊数字,因为找到了原因。你的任务是找到错误并消除它。

public class HowDoICompare {
    public static String whatIs(Integer x) {
        for (Object[] p : specialNumbers) {
            if (p[0] == x)
                return (String)p[1];
        }
        return "nothing";
    }
    
    static final Object[][] specialNumbers = {
        {42, "everything"},
        {42 * 42, "everything squared"},
    };
}

测试用例:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class HowDoICompareTest {
    @Test
    public void test() throws Exception {
        for (Object[] t: tests)
            assertEquals(t[1], HowDoICompare.whatIs((Integer)t[0]));
    }
    
    static final Object[][] tests = {
        {0, "nothing"},
        {123, "nothing"},
        {-1, "nothing"},
        {42, "everything"},
        {42 * 42, "everything squared"},
    };
}

解题

public class HowDoICompare {
    public static String whatIs(Integer x) {
        for (Object[] p : specialNumbers) {
            if (p[0].equals(x)) {
                return (String)p[1];
            }
        }
        return "nothing";
    }
    
    static final Object[][] specialNumbers = {
        {42, "everything"},
        {42 * 42, "everything squared"},
    };
}

后记

这题还是考引用数据类型在“==”与“equals()”的区别。

上一篇下一篇

猜你喜欢

热点阅读