4.2 上机作业
1. 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
package zy; public class hj { public static void main(String[] args) { int b,s,g,sum=0; for(int i=100;i<=999;i++) { b=i/100; s=i/10%10; g=i%10; sum=b*b*b+s*s*s+g*g*g; if(sum==i) { System.out.print(i+" "); } } } }
2.在控制台输出以下图形
package zy; public class hj { public static void main(String[] args) { int i=1; int j=1; for( i=1;i<7;i++) { for( j=1;j<=i;j++) { System.out.print(j); } System.out.println(); } } }
package zy; public class hj { public static void main(String[] args) { int i; int j; int k; for(i=1;i<7;i++) { for( j=i;j>0;j--) { System.out.print(j); } System.out.println(); } System.out .println("\n"); for(i=6;i>0;i--) { for(k=0;k<6-i;k++) { System.out.print(" "); } for(j=1;j<=i;j++) { System.out.print(j); } System.out.println(""); } } }
3. 输入年月日,判断这是这一年中的第几天
package zy; import java.util.Scanner; public class hj { public static void main(String[] args) { int year,month,day,a=0,b=0; Scanner reader=new Scanner(System.in); System.out.println("请输入年份"); year=reader.nextInt(); System.out.println("请输入月份"); month=reader.nextInt(); System.out.println("请输入日"); day=reader.nextInt(); for(int i=1;i<month;i++) { switch(i) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: a=31; break; case 2: if(year%4==0&&year%100!=0||year%400==0) a=29; else a=28; break; case 4: case 6: case 9: case 11: a=30; break; } b=b+a; } b=b+day; System.out.println("这是这一年的第"+b+"天"); } }
4.由控制台输入一个4位整数,求将该数反转以后的数,如原数为1234,反转后的数位4321
package zy; import java.util.Scanner; public class hj { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个四位数"); int x = sc.nextInt(); if(x>999 && x<=9999){ int gewei = x%10; int shiwei = x % 100 / 10; int baiwei = x%1000/100; int qianwei = x/1000; int sum = qianwei + baiwei*10 +shiwei*100 +gewei*1000; System.out.println(sum); } else{ System.out.println("error"); } } }

浙公网安备 33010602011771号