Counting # of 7's in an integer

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:

Code :

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 help!

Re: Counting # of 7's in an integer

Does it compile and run? Does it produce the desired results? What set of numbers did you use to test with?

Re: Counting # of 7's in an integer

Sorry, the teacher gave us a hint that we might consider using integer division or the modulus operator to separate out each digit of n, then check whether it is a seven. So I'm intending to check whether the ones digit is a 7, then divide by 10 to drop that off and check whether the new ones digit is a 7.

It does compile, but for some cases I don't get the correct answer.

For example:

7 gives me 1.

0077 gives me 2.

770 returns nothing.

It seems when the 7 is not on the right hand side of the integer it doesn't count it correctly.

Re: Counting # of 7's in an integer

Quote:

7 gives me 1.

0077 gives me 2.

770 returns nothing.

It seems when the 7 is not on the right hand side of the integer it doesn't count it correctly.

Now let's consider why... What is the condition in which the body of the loop will be executed?

It reads like: while the remainder of number divided by ten is seven.

That is really not what you want to do. What you want to do is check the whole number, every digit, regardless of whether the right most digit is a 7 or not.

So the loop could read like: while number is greater than ten { do my work to check the right most digit and update my number }

or: for each digit in the given number { do my work to check the right most digit }

I would recommend you start with writing down a series of steps to take to solve the problem, and then write code to perform the steps.