简体   繁体   中英

Why does this for-loop only run once?

The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.

My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.

I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets

public class TestingSevens {
    public static void main(String[] args) {
        int sevens = Integer.parseInt(args[0]);

        int count = 0;

        for (int i = 0; i < args.length; i++) {
            if (sevens%10 == 7) {
                count += 1;
            }
            sevens = sevens/10;
            System.out.println(sevens);
        }
        System.out.println(count);
    }
}

The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?

I presume you want to iterate over each digit of sevens . Since sevens initialized from args[0] , the loop limit should match and look at args[0].length() rather than args.length .

for (int i = 0; i < args[0].length(); i++)

An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.

while (sevens > 0) {
    if (sevens%10 == 7) {
        count += 1;
    }
    sevens /= 10;
    System.out.println(sevens);
}

Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)

Below is the corrected code:

public static void main(String[] args) {

    int sevens = Integer.parseInt(args[0]);
    String numberString = String.valueOf(sevens);
    int count = 0;

    for (int i = 0; i < numberString.length(); i++) {
        char c = numberString.charAt(i);        

        if (c == '7') {
            count += 1;
        }

        System.out.println("Input number: " + sevens);
    }
    System.out.println("Count of 7 numbers: " + count);
}

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