java - 确定数字是否为 'insipid' 的方法

标签 java compiler-errors

所以我的任务是编写一个程序来确定一个数字是否平淡。意思是,如果你取一个数字: 例如57,你加上每个数字的平方,5*5 + 7*7,现在就是新数字:74。你继续这样做,直到你得到 58,这意味着这个数字并不平淡,或者你得到 1,这意味着这个数字平淡无奇。 58 只会重复一个始终以 58 结束的序列。

所以我想尝试一些基本的递归,但也许我误解了这里递归的使用。

这是我写的两个相关方法:

public static boolean insipid(int num){

    int dig1 = 0, dig2 = 0, dig3 = 0; // num = 159 for example, dig1 would be 1. Default is 0 in case of a 2 digit number, dig1*dig1 = 0
    if(num == 58){ //The number is not insipid
        return false;
    }
    if(num == 1){ // the number is insipid
        return true;
    }

    if (num < 10){
        insipid(num * num);
    }
    if(num>99){
        dig1 = (int)(num / 100);
        dig2 = (int)((num - 100)/10);
        dig3 = num - (((int)(num / 10))*10);
        insipid(squaresum(dig1,dig2,dig3));
    }
    else{
        dig2 = (int)(num/10); //the 10s place
        dig3 = num - (((int)(num/10)) * 10); // the 1's place
        insipid(squaresum(dig1, dig2,dig3)); //dig1 = 0 so I just pass it along with it.
    }
}

public static int squaresum(int dig1, int dig2, int dig3){
    //Returns the sum of three digits squared.
    return (dig1 * dig1) + (dig2 * dig2) + (dig3 + dig3);
}

它给我一个错误,说只要我向 Insipid() 提供一个数字,它就必须返回一个 boolean 值。但我知道对于给定的任何数字,它总是最终会解析为 58 或 1。所以最终不应该总是返回 true 或 false 以便返回 boolean 值并且错误无效吗?显然事实并非如此,但我是如何看待的。是不是这里使用的递归无效了?

另外,如果你对我如何清理这个有任何建议,我不介意严厉的批评,我的java不是很好。

最佳答案

如果您采用自己的解决方案,唯一缺少的是对 incipid 递归调用的返回语句。

关于java - 确定数字是否为 'insipid' 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851192/

相关文章:

Java:HashMap 的行为方式异常

java - JButton ActionListener 未启动 TimerTask

java - 创建集群需要 InstanceProfile

java - jackson XML 2.9.0 : @JacksonXmlElementWrapper not working with @JsonCreator & @JsonProperty constructor

swift - 有没有办法让Swift编译器忽略错误?

r - 无法安装cubature软件包(配置: error: C compiler cannot create executables)

java - 为什么 'Arrays' 类的方法在 Java 中都是静态的?

gcc - gcc编译器不会在第一个错误时停止

c++ - fatal error C1016 : #if[n]def expected an identifier

makefile - 无法使用Cmake构建