日期:2014-05-20  浏览次数:20649 次

一道简单的JavaSe的题。 我写的太复杂,求好代码
Java code
package com.kang.test01;

public class Exercise01 {
    
    private int num = 0;
    private int levelOne =0;
    private int levelTwo =0;
    private int levelThree =0;
    private int levelFour =0;
//    private int temp1 = 0;
    public Exercise01(int num) {
        // TODO Auto-generated constructor stub
        this.num = num;
        if(!this.checkRight(num))
        {
            System.out.println("Your number is not right for here !" +
                    "检查是否是四位数    系统退出");
            System.exit(-1);
        }
        
    }
    
    /*1、    使用算术运算符得到一个4位十进制数的各位数
     * 字并输出,然后输出该数的逆序数和各位数字平方后相加的和。*/
    //查一下是否是四位数
    public boolean  checkRight(int num)
    {
        if(num >=1000 && num <=9999)
        {
            return true;
            
        }
        
        return false;
        
    }
    //输出该数的逆序数
    public void reverse()
    {
        System.out.println(""+this.levelOne+this.levelTwo+this.levelThree+this.levelFour);
    }
    
    public void getEachNum()
    {
        System.out.println ("这个数的千位是"+this.getLevelFour() + "\t" +"这个数的百位是"+
                this.getLevelThree() + "\t" +"这个数的十位是"+this.getLevelTwo() + "\t"
                +"这个数的个位是"+ this.getLevelOne() );
    }
//取这个数的个位
    public int getLevelOne() {
        
        this.levelOne = num % 1000 % 100 % 10;
        return levelOne;
    }
//取这个数的十位数
    public int getLevelTwo() {
        
        this.levelTwo = num %100 / 10;
        return levelTwo;
    }
//取这个数的百位数
    public int getLevelThree() {
        
        this.levelThree = num % 1000 / 100;
        return levelThree;
    }
//取这个数的千位数 
    public int getLevelFour() {
        
        this.levelFour = num / 1000;
        return levelFour;
    }

    public int getSumWithEach()
    {
        return levelFour + levelThree + levelTwo +  levelOne;
        
    }
}



------解决方案--------------------
请问楼主的需求是什么?
------解决方案--------------------
各位数字平方后相加的和


我在你的程序中没看到
------解决方案--------------------
public class TestMath
{
public static void main(String[] args) throws Exception
{
int num = 1562;
int[] digits = new int[4];//将各位数存在数组里
int sum = 0;

System.out.print(num + "的逆序数是:");
for (int i = digits.length - 1; i >= 0; i--)
{
digits[i] = num % 10;
num /= 10;
System.out.print(digits[i]);//逆序输出
sum += digits[i] * digits[i];
}

System.out.println("各位数和的平方是:" + sum);
}
}