0

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!

2
Contributors
1
Reply
7
Views
4 Years
Discussion Span
Last Post by dmanw100
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.