使用递归方法查找偶数

时间:2014-04-11 01:42:18

标签: java recursion user-input

我试图让下面列出的代码从用户接收int输入,然后在该int中查找偶数的数量。当我尝试打印退货时,我收到错误...有什么帮助吗?

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);


}

}

具体而言,此声明中存在错误:

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

1 个答案:

答案 0 :(得分:2)

main中您需要更改:

countEvenDigits(number);

为:

int result = countEvenDigits(number);

否则,您正在访问println

中不存在的变量