簡體   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