第十周上机课作业\
1.编写一个方法,实现冒泡排序(由小到大),并调用该方法
package gkd; import java.util.Scanner; public class test1 { public static void mppx() { Scanner input=new Scanner(System.in); System.out.println("请输入10个数"); int []a=new int[10]; for (int i = 0; i < a.length; i++) { a[i]=input.nextInt(); } for (int i = 0; i < a.length-1; i++) { for (int j = 0; j < a.length-i-1; j++) { if(a[j]>a[j+1]){ int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } System.out.println("冒泡排序后"); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } public static void main(String[] args) { mppx(); } }
2.编写一个方法,求整数n的阶乘,例如5的阶乘是1*2*3*4*5。 [必做题]
package gkd; import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入一个数: "); int n = sc.nextInt(); jiecheng(n); } public static int jiecheng(int n) { int sum = 1; for (int i = 1; i <= n; i++) { sum *= i; } System.out.println("factorial(" + n + ")=" + sum); return sum; } }
3.编写一个方法,判断该年份是平年还是闰年。[必做题]
package gkd;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("请输入一个年份:");
int year=input.nextInt();
if ((year%4==0&&year%100!=0||year%400==0)) {
System.out.println("此年份为闰年");
}
else{
System.out.println("此年份不是闰年");
}
}
}
4.课堂没完成的menu菜单,实现幸运抽奖功能
package gkd; import java.util.Scanner; import java.util.Random; public class Demo { public static void mainMenu() { // TODO Auto-generated method stub Scanner input=new Scanner(System.in); System.out.println("欢迎使用本系统"); System.out.println("1.登录"); System.out.println("2.注册"); System.out.println("3.幸运抽奖"); System.out.println("4.退出"); System.out.println("请选择"); int i=input.nextInt(); switch (i) { case 1: login(); break; case 2: reg(); break; case 3: lucky(); } } private static void lucky() { Scanner input=new Scanner(System.in); Random r=new Random(); int x=r.nextInt(10); System.out.println("幸运数字为"+x); System.out.println("请输入四位幸运卡号"); int number=input.nextInt(); if (number/100%10==x) { System.out.println("该卡号为幸运卡号"); }else{ System.out.println("该卡不是幸运卡号"); } returnMain(); } public static void returnMain() { Scanner input=new Scanner(System.in); System.out.println("是否返回主菜单?"); if (input.next().equalsIgnoreCase("yes")) mainMenu(); else System.out.println("输入错误"); } public static void login() { Scanner input=new Scanner(System.in); System.out.println("输入用户名"); String uname=input.next(); System.out.println("输入密码"); String upwd=input.next(); if (uname.equals("xsy")&&upwd.equals("666")) { System.out.println("登陆成功"); } else{ System.out.println("输入错误"); } returnMain(); } public static void reg() { Scanner input=new Scanner(System.in); System.out.println("请输入要注册的用户名"); String uname=input.next(); System.out.println("请输入注册密码"); String upwd=input.next(); System.out.println("注册成功"); returnMain(); } public static void main(String[] args) { // TODO Auto-generated method stub mainMenu(); } }