需求:
1.创建一个任意长度的int类型数组(在此定义数组长度为10);
2.采用键盘录入(scanner)的方式给数组赋值;
3.通过冒泡排序,将数组从小到大排序;
4.使用增强for遍历数组,并打印结果
代码实现:(类名:sort)
public class Sort {
public static void main(String[] args) {
int[] arr = new int[10]; //定义一个长度为10的int类型数组
Scanner sc = new Scanner (System.in); //创建键盘录入对象
for (int y = 0;y < arr.length; y++) { //通过普通for循环给数组赋值
System.out.println("请输入第"+(y+1)+"数字"); //控制台提示客户键盘录入数字
int num = sc .nextInt(); //定义int类型num,接受录入的数字
arr[y] = num; //将接受的数字通过循环,依次赋值给数组
}
for (int x = 0; x < arr.length -1 ;x++ ) { //最外层循环表示需要排序的数的个数
for (int i = 0; i <arr.length -x -1 ; i ++) { //内层循环表示每一个数,需要对比的个数
int temp = arr[i]; //定义第三方数,用于接受和赋值
if (arr[i] > arr[i+1]) { //比较相邻数的大小,此处是按从小到大排序,所以左侧数大则执行if里面程序
arr[i] = arr[i + 1]) ;
arr[i + 1] = temp;
}
}
}
for (int a : arr) { //通过增强for遍历排序后的数组
System.out.print(a +"\t"); //打印输出排序后的结果,print表示不换行输出,"\t"是空格符
}
}
}