0

I am trying to have the code listed below receive an int input from user, then find amount of even numbers in that int. I'm getting an error when I try to print the return... any help?

import java.util.Scanner;
public class evenDigits {

public static int countEvenDigits(int number){
    if (number == 0)
        return 0;
    else{
        int lastDigit = number % 10;
        int result = countEvenDigits(number / 10);
        if (lastDigit % 2 == 0)
            return result + 1;
        else
            return result;
    }
}

public static void main(String[] args) {

    System.out.println("Please enter an integer.");
    Scanner keyboard = new Scanner(System.in);
    int number = keyboard.nextInt();

    countEvenDigits(number);

    System.out.println("There are " + result + " even digits in " + number);


}

}

Specifically, there is an error in this statement:

System.out.println("There are " + result + " even digits in " + number); 
4
  • Specifically, there is an error in this statement: System.out.println("There are " + result + " even digits in " + number); Commented Apr 11, 2014 at 1:43
  • You're not receiving the return value from countEvenDigits in main! You haven't even defined result in main. Commented Apr 11, 2014 at 1:44
  • Try int result = countEvenDigits(number); in your main. result is only declared in the method, not in your main. Commented Apr 11, 2014 at 1:47
  • No, they can be separate variables. Commented Apr 11, 2014 at 1:48

1 Answer 1

2

In main you need to change:

countEvenDigits(number);

to:

int result = countEvenDigits(number);

Otherwise, you're accessing a nonexistent variable in your println

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.