Hi everyone, I'm in an entry level Java class and I'm supposed to be able to count the # of 7's within an integer. I've read the chapters and looked online for help but can't seem to figure it out. We just learned loops (do, while, for) and if statements so I'm thinking I need to use some of those to solve it. Here's what I came up with so far:

public class CountSevens 
{
public static void main(String[] args) 
{
    // ask the user for input and assign to a variable
    System.out.print("Please enter an integer: ");
    Scanner in = new Scanner(System.in);
    int number = in.nextInt();

    // calculate the number of digits that have a 7
    int count = 0;
    if (number == 0)
    {
        System.out.println("There are no 7's.");
    }
    while (number % 10 == 7)
    {
        count++;
        number = number/10;     
    }
    System.out.println(count);
}
}

Thanks for any advice!

This is a good start, but remember the while() will exit if the test condition fails. If the number 7773 is entered this loop will fail (since 7773 % 10 is 3, which does not equal 7). I would suggest a for() loop that tested if the integer was still greater than zero. Something like for(int i = number; i > 0; i = i / 10) and perform the modulus test in the body with an if statement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.