Java初学练习答案(循环)

/*
题目如下: 1 (for 循环)*编程找出四位整数abcd 中满足下述关系的数。
(ab+cd)(ab+cd)=abcd
2 (循环)*读入一个整数n,输出如下图形
n = 3
*
***
*****
n = 4
*
***
*****
*******
思路:读入的整数n,就是外层循环的循环次数。
对于每一行,要做的事情:1. 输出若干个空格;2. 输出若干个星;3. 换行。
提示:输出不换行,用System.out.print()
3. (循环)**求水仙花数。所谓水仙花数,是指一个三位数abc,如果满足a3+b3+c3=abc,则abc 是水仙花数。
4. (循环)**输入一个整数,计算它各位上数字的和。(注意:是任意位的整数) 空格: n-1 依次递减 星号: 1 3 5 7
1 2 3 4 */ package MyTest; import java.util.Scanner; public class ChapUnitOne {
//第一题答案
public void AnswerOne()
{
int a,b,c,d; /*
int i = 1234; a = i / 1000;
b = i / 100 % 10;
c = i / 10 % 10;
d = i % 10; System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
*/ for(int i = 1000;i<9999;i++)
{
a = i / 1000;
b = i / 100 % 10;
c = i / 10 % 10;
d = i % 10; int ab = a*10+b;
int cd = c*10+d;
int ad = ab+cd;
if(ad*ad == i)
{
System.out.println(i);
}
}
}
//第二题答案
public void AnswerTwo()
{
Scanner num = new Scanner(System.in); System.out.println("请输入一个整数");
int mynum = num.nextInt(); for(int i=0; i<mynum; i++)
{
for (int j=0; j<=mynum-i-1; j++)
{
System.out.print(" ");
}
for (int j=0; j<=i*2; j++)
{
System.out.print("*");
}
System.out.println();
}
}
//第三题答案
public void AnswerThree()
{
for(int i = 100;i<999;i++)
{
int a = i / 100 % 10;
int b = i / 10 % 10;
int c = i % 10; if(a*a*a+b*b*b+c*c*c == i)
{
System.out.println("该数字为水仙花数:"+i);
}
}
}
//第四题答案
public void AnswerFour()
{
Scanner num = new Scanner(System.in);
System.out.println("请输入一个整数:");
int mynum = num.nextInt(); int sum = 0;
/*
int a = i / 100 % 10;
int b = i / 10 % 10;
int c = i % 10;
*/
System.out.print("Sum = ");
while (mynum>0)
{
int temp = mynum%10;
sum += mynum%10;
mynum = mynum/10; if(mynum !=0 )
System.out.print(temp+"+");
else
System.out.print(temp);
}
System.out.println(" = "+sum);
} public static void main(String[] args) {
Scanner i = new Scanner(System.in);
System.out.println("请输入您想查看答案的题号:");
int num = i.nextInt();
ChapUnitOne myanswer = new ChapUnitOne();
switch(num)
{
case 1:
myanswer.AnswerOne();
break;
case 2:
myanswer.AnswerTwo();
break;
case 3:
myanswer.AnswerThree();
break;
case 4:
myanswer.AnswerFour();
break;
}
}
}

  

上一篇:Windows Service的官方描述,抄下来(不写obj就是LocalSystem)


下一篇:实现CI/CDk8s高可用集群搭建总结以及部署API到k8s