Now that you've learned about Java arrays, we'll output the benefits of arrays and usage examples.
This time, we will compare how to use variables and arrays using a score management program, and explain the merits of using arrays.
test
public class Main {
public static void main(String[] args) {
int sansu = 20;
int kokugo = 30;
int rika = 40;
int eigo = 50;
int syakai = 80;
int sum = sansu + kokugo + rika + eigo + syakai;
int avg = sum / 5;
System.out.println("Total score:" + sum);
System.out.println("Average score:" + avg);
}
}
Total score: 220
Average score: 44
This is not a problem, but there are two inconveniences.
—— As the number of subjects increases, the code becomes cumbersome and redundant. --Cannot process all at once
test
public class Main {
public static void main(String[] args) {
int[] scores = {20, 30, 40, 50, 80};
int sum = scores[0] + scores[1] + scores[2] + scores[3] + scores[4];
int avg = sum / scores.length;
System.out.println("Total score:" + sum);
System.out.println("Average score:" + avg);
}
}
Total score: 220
Average score: 44
The execution results are the same for both, but using an array makes the code cleaner, and it's a little better. I understand the merits of using arrays like this (?) I will explain each one.
Data that stores multiple data of the same type ** in ** sort order **. In addition, the order of arrangement is called a subscript, and it is a rule that starts from ** 0 **. In a program using arrays, 20 points are the 0th element.
2 Steps are required to create an array.
Element type [] Array variable name
int[] scores;
scores = new int[5];
new is called the new operator, and you can create the specified number of elements in [].
int[] scores = new int[5];
int num = scores.length;
Recommended Posts