1. 已有一个升序排列的整数数组(含20个整数),要求从键盘输入一个整数后,将该数插入数组,并保持升序,输出该数组的数值验证程序的正确性。
4 回答
已采纳
是王小二呀
TA贡献88条经验 获得超19个赞
package test_Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Scanner; public class ArrayTest { public static void main(String[] args){ ArrayTest at = new ArrayTest(); at.sortArray(); } Object sortArray(){ int[] array = new int[]{-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9}; Collection<Integer> arrayList = new ArrayList<Integer>(); System.out.println("Old array's length:"+array.length); for(int i=0;i<array.length;i++){ System.out.print(" "+array[i]); arrayList.add(new Integer(array[i])); } System.out.print("\n"+"Please input a number:"); arrayList.add(new Integer(input())); System.out.println("Current array'length:"+arrayList.size()); Object[] now=arrayList.toArray(); Arrays.sort(now); for(Object currentArray:now){ System.out.print(" "+currentArray); } return arrayList; } static int input() { int input = (new Scanner(System.in)).nextInt(); return input; } }
我在排序之前用了一个匿名类,这时候没有执行排序直接就加入然后输出了,这个才是正确程序,有点儿小区别;不好意思啊。。
是王小二呀
TA贡献88条经验 获得超19个赞
package test_Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Scanner; public class ArrayTest { public static void main(String[] args){ ArrayTest at = new ArrayTest(); at.sortArray(); } Object sortArray(){ int[] array = new int[]{-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9}; Collection<Integer> arrayList = new ArrayList<Integer>(); System.out.println("Old array's length:"+array.length); for(int i=0;i<array.length;i++){ System.out.print(" "+array[i]); arrayList.add(new Integer(array[i])); } System.out.print("\n"+"Please input a number:"); arrayList.add(new Integer(input())); System.out.println("Current array'length:"+arrayList.size()); Arrays.sort(arrayList.toArray()); for(Object currentArray:arrayList.toArray()){ System.out.print(" "+currentArray); } return arrayList; } static int input() { int input = (new Scanner(System.in)).nextInt(); return input; } }
添加回答
举报
0/150
提交
取消