Home >Java >javaTutorial >What are the common operations on one-dimensional arrays in Java?

What are the common operations on one-dimensional arrays in Java?

WBOY
WBOYforward
2023-04-18 13:13:031458browse

1. Sum the arrays

public class Main {
    public static void main(String[] args) {
        int num[]={1,2,3,4,5,6,7,8,9,10};    //定义一维数组
        int sum = 0;
        System.out.println("一维数组中个元素之和为:");
        for(int i=0;i<num.length;i++){
            System.out.print(num[i]);
            if (i==9) {
                System.out.print("=");            }
            else if (i<9){
                System.out.print("+");
            }
            sum=sum+num[i];
        }
        System.out.print(sum);
    }
}

2. Find the average of the array

Find the average score of five people and use a loop to get it Sum

int [ ] scores = {60, 80, 90, 70, 85};
int sum = 0;
double avg;
for(int i = 0; i < scores.length; i++){
     sum = sum + scores[i];
}
avg = sum / scores.length;
 
for(int score:scores)//for的强循环
{
sum += score;
}

3. Call the specified array

Use the subscript to call and must start from 0.

The following example: the second and third numbers in garb are called

public class Main {
    public static void main(String[] args) {
        int[] garb=new int[]{1,2,3};
        garb[1]=100;
        garb[2]=garb[1]*2;
        System.out.println(garb[2]);
    }
}

The above is the detailed content of What are the common operations on one-dimensional arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete