学会数组的声明方法。
并写一段数组反转的代码。
package qqq;
public class HelloWorld {
public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } System.out.println("\n翻转数组,结果如下:"); int[] b = new int[10];// 重新声明一个同样长度的数组,用来存放翻转后的数组 for (int i = 0; i < b.length; i++) { b[i] = a[a.length - (i + 1)];// 将原来数组从最后一位开始,所有的数值全部按顺序输入新的数组 System.out.printf("%d ",b[i]);// 将他们打印出来
} } }
随机生成一段整数数组,并用选择排序,从小到大排列:
package qqq;
public class HelloWorld {
public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } for (int i = 0; i < a.length - 1; i++) { for (int j = i+1; j < a.length; j++) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } }// 将数组按照选择排序从小到大排列 System.out.println("\n经过选择排序,数字从小到大顺序如下:"); for (int i = 0; i < a.length; i++) { System.out.printf("%d ",a[i]); } } }
随机生成一段整数数组,并用冒泡排序,从小到大排列:
package qqq;
public class HelloWorld {
public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } 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+1]; a[j+1] = a[j]; a[j] = temp; } } }
// 将数组按照冒泡排序从小到大排列 System.out.println("\n经过冒泡排序,数字从小到大顺序如下:"); for (int i = 0; i < a.length; i++) { System.out.printf("%d ",a[i]); } } }
用增强型for循环,在一个随机数组中找到最大的数字:
package qqq;
public class HelloWorld {
public static void main(String[] args) { int[] a = new int[10];// 声明数组,长度10 System.out.println("生成一个随机数组,数字顺序如下:"); for(int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100);// 为数组的每一位随机赋予一个数值 System.out.printf("%d ",a[i]);// 并将整个数组打印出来 } int max = -1; for (int i : a) { if (i > max) { max = i; } } System.out.printf("\n找到数组中最大的数字如下:%d",max);
} }
领取专属 10元无门槛券
私享最新 技术干货