繁体   English   中英

检查乘法表数组

[英]checking multiplication table arrays

我的代码不断返回false我在做什么错? 这是我得到的反馈。 checkTable()仅应在找到不正确的条目时返回false。

失败: java.lang.AssertionError: checkTable()当索引0处的条目不等于0时, java.lang.AssertionError: checkTable()应该返回false。

/**
         * This method checks if an array of ints contains a correctly calculated
         * multiplication table.<br/>
         * Precondition: multTable IS NOT null. (PRECONDITIONS SPECIFY RESPONSIBILITIES
         * ON A METHOD'S CALLER; YOU SHOULD ASSUME THIS IS TRUE.)
         *
         * @param constant
         *            Value used to check the multiplication table.
         * @param multTable
         *            Table to be checked.
         * @return True if every entry in the array stores the value of {@code constant}
         *         * the index for that entry; or false if at least one entry is
         *         incorrect.
         */
        public static boolean checkTable(int constant, int[] multTable) {
            int i=0;

            for(i=0;i<multTable.length;i++){
                int mult = constant*i;
                if(mult==multTable[i]) {
                    return true;
                }

            }
            return false;
        }

现在,如果Array只有一个有效条目,您将立即返回true

if(mult==multTable[i]) {
     return true;
}

它必须是相反的方式:

for(i=0;i<multTable.length;i++){
     int mult = constant*i;
     if(mult!=multTable[i]) {
         return false;
     }
 }
 return true;

只需逐行浏览代码。 假设常量为“ 5”,输入为new int [] {0,15,38}; 这显然不是乘法表。

int i = 0; :我现在存在。 i的值现在为0。

for (int i = 0; i < multTable.length; i++) {我们将循环3次。 我们使用第一个值(0)进入循环。

int mult = constant * i; :现在存在多个。 mult的值为0(因为5 * 0为0)。

if (mult == multTable[i]) return true; :倍数为0; 示例multTable输入中的第一项为0。因此,如果if触发器且整个方法返回,则值为true。 其余元素完全不会检查。

解决方法显然是在第一个元素正确时返回。 当您遇到“错误”时,您立即知道问题“这是一个有效的乘法表”的答案为假。 但是,当您输入正确的条目并不表示您知道答案。 您必须继续前进。

这有点作业的味道,所以我让您荣幸地弄清这意味着什么以及如何修复代码。

注意:这是解决代码问题的方法:通过代码进行推理。 您检查代码的实际作用(使用调试器,或者如果这是目前System.out.println了解的桥梁,请添加许多System.out.println语句)。 您的代码与您认为的应做的不匹配的地方就是您发现错误的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM