java简单题目

来源:百度知道 编辑:UC知道 时间:2024/07/02 22:55:59
题目:5-50的数字,要求输出5到50的平方数后的每一位数加起来,例如5*5=25,则输出2+5=7.最后答案系7,如12*12=144,则输出1+4+4=9,最后答案系9,要求用for语句同if语句。
可以给出一个是初学者看得明白的吗? 还有更简单的吗?还有更简单的吗?

一个没有用到任何类的程序实现的。我想初者可以看得懂。

public class Print {

public static void main(String args[]) {
for (int w = 5; w < 51; w++) {
int n = w * w;
int[] a = new int[100];
int i = 0;
while (n > 10) {//这个循环你应可以看懂
a[i++] = n % 10;//救出这一数的个们,并放到数组里
n = n / 10;//算出这个去掉个们后的数是多少,并放到n里
}
a[i] = n;//把最后的那个数放进来。

int sum = 0;
for (int j = 0; j < a.length; j++) {//把所有数加起来
sum += a[j];
}
System.out.println("对" + w + "的平方处理后的结果为:" + sum);

}
}
}

public class Test {

public static void main(String[] args) {
int from = 5;
int to = 50;
int temp = 0;
char [] chs = null ;
for(int i = from; i <= to; i ++) {
temp = i * i;
int result = 0;
chs = String.valueOf(temp).toCharArray();
for(char c: chs) {
result += Integer.valueOf(