簡體   English   中英

Java循環未按預期打印結果

[英]Java Loop Not Printing Result As Expected

package com.company;

public class Main {

    public static int deleteFives(int start, int end) {
        int count = 0;
        for (int j = start; start < end; j++) {
            count++;
        }
        return count;
    }
    public static void main(String[] args) {
        int result = deleteFives(1, 100);
        System.out.println(result);
    }

}

當我實際調用該方法時,此循環沒有任何輸出。 我只是想顯示“計數”。 我的輸出實際上是空白的。 我很困惑,因為我看不到任何缺陷。

因為在循環定義中未使用j。 您在代碼中寫了start <end而不是j <end。 下面的代碼是打印結果

public static int deleteFives(int start, int end) {
    int count = 0;
    for (int j = start; j < end; j++) {
        count++;
    }
    return count;
}

public static void main(String[] args) {
    int result = deleteFives(1, 100);
    System.out.println(result);
}

變量J不用於比較。 在條件檢查中將變量J與start交換。

看到這個並像這樣練習:

package com.practice;

public class Main {

    private static int startCounting(int start, int end) {
        int count = 0;
        while(start++<end)
            ++count;
        return count;
    }

    public static void main(String[] args) {
        int countingResult = startCounting(1, 100);
        System.out.println(countingResult);
    }
}

start <end似乎在循環中是錯誤的。 我認為應該是j <end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM