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
Release: 2023-04-18 13:13:03
forward
1444 people have browsed it

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);
    }
}
Copy after login

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;
}
Copy after login

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]);
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template