简体   繁体   中英

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);
    }

}

This loop is giving no output when I actually call the method. I'm simply trying to have the "count" display. My output is literally blank. I'm very confused, as I can't see any flaws.

because j was not used in loop definition. You wrote start < end in your code instead of j < end. Code below is printing result

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);
}

Variable J isn't used to compare. Swap variable J with start in the condition check.

See this and Practice like this:

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 seems wrong in the loop. I think it should be j< end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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