JAVA基础:数组常见案例

1.数组找最值

package com.itheima.arry;

public class ArrayDemo7 {
    public static void main(String[] args) {
        //掌握数组元素求最值
        int[] faceScore={15,9000,10000,20000,9500,-5};
        int max=faceScore[0];
        for (int i = 1; i < faceScore.length; i++) {
//            if(max<faceScore[i]){
//                max=faceScore[i];
//            }

max=max<faceScore[i]?faceScore[i]:max; } System.out.println(max); } }


 

 

2.数组反转

package com.itheima.arry;

public class ArrayDemo8 {
    public static void main(String[] args) {
        int[] arr=new int[]{10,20,30,40,50};
        for (int i = 0,j=arr.length-1; i < j; i++,j--) {
            int temp=arr[j];
            arr[j]=arr[i];
            arr[i]=temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
}

 

 

 

3.随机排名案例:

package com.itheima.arry;

import java.util.Random;
import java.util.Scanner;

public class ArrayDemo9 {
    public static void main(String[] args) {
        int[] codes=new int[5];
        Scanner a=new Scanner(System.in);
        for (int i = 0; i < codes.length; i++) {
            System.out.println("请您输入工号"+(i+1));
            codes[i]=a.nextInt();
        }
        Random sr=new Random();
        for (int i = 0; i < codes.length; i++) {
            int index=sr.nextInt(codes.length);
            int temp=codes[i];
            codes[i]=codes[index];
            codes[index]=temp;
        }
        for (int i = 0; i < codes.length; i++) {
            System.out.print(codes[i]+" ");
        }
    }
}

 

posted @ 2024-02-28 21:38  小彭先森  阅读(11)  评论(0编辑  收藏  举报