猿问

如何修复“11”不断重复

我试图使代码打印范围内的回文数字(10到1000),但它不断返回11


 public class Problem{


    static int temp=0;


    static int isReverse; 


    public static int revNum(int d, int n){


        for (int i = 0; i<(Math.log10(d)); i++) {

            temp *= 10;

            temp += n%10;

            n = (n - (n%10))/10;


        }

        return temp;

    }   


    public static int checkNum(int n) {

        if(revNum(n,n) == n) {

            isReverse = n;

        }

        return isReverse;

    }


 public static void main(String[] args) {


        for(int i = 10; i <1000; i++) {

                 System.out.println(checkNum(i));

             }

    }

}

我期望输出为11,22,33,44等,但实际输出是11,11,11...(重复正确的次数,但只有一个值)。


慕容森
浏览 112回答 1
1回答

哈士奇WWW

就像其他人在这里回应的那样,在这种情况下,您并不真正需要静态字段。局部变量就足够了。另外,请考虑该方法正在做什么。您总是看到打印 11 的原因是,从 返回的整数为 11,直到 if 语句 中的条件返回 true。checkNumcheckNumrevNum(n,n) == n例如,当 i = 10 时,条件将返回 false,从而返回或 0。当 i = 11 时,条件将返回 true,从而设置为 11 并打印出来。当 i = 12 时,条件将返回 false。并且由于在这种情况下不会更改,因此返回并打印出该变量的当前值11。随着循环的进行,将打印出 11 个实例的 11 个实例,因为下次返回 true 是 n = 22 时。revNum(10,10) == 10isReverserevNum(11,11) == 11isReverserevNum(12,12) == 12isReverserevNum(n,n) == n相反,您应该做的是将 的返回类型更改为布尔值,以检测此条件何时返回 true。当它发生时,只有这样,您才应该在主方法中打印循环中的数字,以便您可以看到循环范围内的哪些数字是回文的。checkNumi// these variables are not really necessary// int temp = 0;// int isReverse;public static int revNum(int d, int n){&nbsp; &nbsp; int temp = 0;&nbsp; &nbsp; for (int i = 0; i<(Math.log10(d)); i++) {&nbsp; &nbsp; &nbsp; &nbsp; temp *= 10;&nbsp; &nbsp; &nbsp; &nbsp; temp += n%10;&nbsp; &nbsp; &nbsp; &nbsp; n = (n - (n%10))/10;&nbsp; &nbsp; }&nbsp; &nbsp; return temp;}&nbsp; &nbsp;public static boolean checkNum(int n) {&nbsp; &nbsp; return revNum(n,n) == n;}public static void main(String[] args) {&nbsp; &nbsp; for(int i = 10; i <1000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(checkNum(i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答