闲暇之余,我觉得巩固基础还是很有必要的,不论逻辑是否清楚,有时候就算是非常简单的知识点也会被慢慢遗忘,因为平时工作中不太会注意了,今天写了一个利用数组存储数据,然后使用冒泡可以升序降序排列的一个游戏。
public class JavaTest07 { public void CaoZuo(){ ArrayList list = new ArrayList(); Scanner scanner = new Scanner(System.in); boolean flag = true; while(flag){ System.out.println("请选择要进行的操作:"); System.out.println("【0】:输入数据"); System.out.println("【1】:升序排列"); System.out.println("【2】:降序排列"); System.out.println("【3】:退出"); int i = scanner.nextInt(); /*if(i == 0){ System.out.println("请输入数字:"); int sc = scanner.nextInt(); list.add(sc); }else if (i == 1) { DaYin( ShengXu(ShuZu(list)) ); }else if (i == 2) { DaYin( JiangXu(ShuZu(list)) ); }else if (i == 3) { System.out.println("谢谢!再见..."); flag = false; }else { System.out.println("您的输入有误,请重新操作..."); }*/ switch (i) { case 0: System.out.println("请输入数字:"); int sc = scanner.nextInt(); list.add(sc); break; case 1: DaYin( ShengXu(ShuZu(list)) ); break; case 2: DaYin( JiangXu(ShuZu(list)) ); break; case 3: System.out.println("谢谢!再见..."); break; default: System.out.println("您的输入有误,请重新操作..."); break; } } } public int[] ShengXu(int[] li){ System.out.println("按升序排列"); for(int i=0; i<li.length; i++){ for(int j=i+1; j<li.length; j++){ if(li[i]>li[j]){ int temp = li[i]; li[i] = li[j]; li[j] = temp; } } } return li; } public int[] JiangXu(int[] li){ System.out.println("按降序排列"); for(int i=0; i<li.length; i++){ for(int j=i+1; j<li.length; j++){ if(li[i]<li[j]){ int temp = li[i]; li[i] = li[j]; li[j] = temp; } } } return li; } public int[] ShuZu(ArrayList list){ int[] array = new int[list.size()]; for(int i=0; i<list.size(); i++){ array[i] = (Integer) list.get(i); } return array; } public void DaYin(int[] array){ System.out.println("开始打印..."); String s = ""; //将数组拼成字符串 for (int i = 0; i < array.length; i++) { //System.out.print(array[i] + ","); s += array[i] + ","; } //去掉字符串最后的标点 String str = s.substring(0, s.length()-1); System.out.println("【"+str+"】"); } /** * @param args */ public static void main(String[] args) { JavaTest07 jt = new JavaTest07(); jt.CaoZuo(); } }
时间: 2024-11-03 22:14:03