Java程序写入从0到10的所有Neon数

时间:2018-07-06 00:00:06

标签: java

我试图找到0到10之间的霓虹灯,但显示9不是霓虹灯。 请找到程序错误的地方。 (霓虹灯数字是该数字的平方的位数之和等于该数字的数字)
程序:

class Neon
{
    public static void main(String [] args)
    {
        int n,m,y=0,z=0;
        for(n=0;n<11;n++)
        {
        m=n;

        int x=m*m;
        while(x!=0)
        {
          y=x%10;
          z=z+y;

          x=x/10;
        }
        if(z==n)
        {
        System.out.println(n+" is a Neon no.");
        }
        else
        {
            System.out.println(n+" is not a Neon no.");
        }
    }
    }
}

输出:
0是霓虹灯。
1是霓虹灯号。
2不是霓虹灯。
3不是霓虹灯。
4不是霓虹灯编号。
5不是霓虹灯。
6不是霓虹灯。
7不是霓虹灯。
8不是霓虹灯。
9不是霓虹灯。
10不是霓虹灯。

1 个答案:

答案 0 :(得分:1)

尝试一下:

public class Neon
{
private static int findDigitSum(int num) {
    return (num == 0) ? num : num % 10 + findDigitSum(num / 10);
}

public static void main(String [] args)
{
    int n,m,z=0;

    for(n=0; n<11; n++)
    {
      m=n;

      int x=m*m;

      z= findDigitSum(x);//It's much easier to use a separate method to calculate sum of digits 

      if(z==n)
      {
        System.out.println(n+" is a Neon no.");
      }
      else
      {
        System.out.println(n+" is not a Neon no.");
      }
    }
}
}

输出:

0 is a Neon no.
1 is a Neon no.
2 is not a Neon no.
3 is not a Neon no.
4 is not a Neon no.
5 is not a Neon no.
6 is not a Neon no.
7 is not a Neon no.
8 is not a Neon no.
9 is a Neon no.
10 is not a Neon no.

建议: 声明变量时,请始终明确(如n表示数字,z表示digitSum)。您在代码中使用了一个字母变量,这使其他人很难理解您的代码做什么。