[Java] Array

Array

: sunny: Combine multiple data together. Something like a set of variables.

Example.java


public class Main {
	public static void main(String[] args) {
	    String fruit1 = "Apple";
	    String fruit2 = "Mandarin orange";
	    String fruit3 = "Strawberry";
	    String fruit4 = "melon";
	    String fruit5 = "banana";
	    
		System.out.println(fruit1);
		System.out.println(fruit2);
		System.out.println(fruit3);
		System.out.println(fruit4);
		System.out.println(fruit5);
	}
}

The above is programming to display the type of fruit. This is not a mistake, but every time I add more fruit types As the number of the variable fruit increases, how many System.out.println ~ will be created? : disappointed_relieved: The more numbers attached to the variable fruit, the more likely it is to make a mistake. Above all, it's annoying: sweat_smile:

** Array ** is useful in such cases: smile:

Before explaining how to write, what is an array? I'll explain that: smile:

The image of my array is

倉庫.jpg

It is a warehouse.

As you can see from the image, there are shelves in the warehouse, and cardboard boxes are lined up on the shelves.

One of these cardboard boxes contains an apple. Another cardboard box contains oranges. And again, there are fruits in each type of cardboard, such as ...

This cardboard is called ** element **. Fruits such as apples and tangerines are called ** values **.

ダンボール.png

And these cardboard boxes (elements) are neatly arranged on a shelf called fruit. The ** array ** is a state in which cardboard boxes (elements) are neatly arranged on this shelf.

棚.png

The cardboard boxes are neatly arranged and lined up, but since I haven't written anything, I have no idea what's inside as long as I open it: worried:

Therefore, I decided to assign a number to each cardboard (element) and manage it. This number is called ** subscript (or index) **. This is a subscript, but there is a little caution. ** It is a rule that always starts from 0 **.

[0] Apples [1] Mandarin oranges [2] Strawberries ・ ・ ・ It will be. So forget to start with [0]

I want an apple cardboard (element), so get the [1] cardboard!

Then, mandarin oranges will come: sweat_smile:

: sunny: Easy summary: sunny: Array (shelf): Elements managed by subscript numbers starting from 0 are stored. Element (cardboard): A value is stored. Value: The contents of the element (here, fruits such as apples and oranges)

How to write an array

Now that we've explained the image of an array, let's actually explain how to write an array: smile:

1. 1. Declaration of array variables
2. Creating and assigning elements

The array requires two steps. First of all, 1. From the array variable declaration: smile:

1. 1. Declaration of array variables

Ever when creating variables

int number; String name;

Such,

Type variable name

I made a declaration to prepare a new box to put variables from now on. This time it's an array version of this: smile: In the previous explanation

("` Д´) "<Prepare a new shelf!

Is the declaration of the array variable.

Lecture.


Element type[]Array variable name

If you apply this ceremony to the fruit program

Example.java


String[] fruits

And a new shelf will be prepared: smile: As a caveat ... : sunny: No space is required between the model name and []. : sunny: The array variable name can be any name you like, but it should be plural.

2. Creating and assigning elements

Earlier, the declaration of array variables provided a new shelf for fruit. Nothing has been placed here yet. There are only shelves. So I will give you a new order.

("` Д´) "<Bring 5 new cardboard boxes and put them on the shelf!

The ceremony is

Lecture.


Array variable name=new type[Element count]

And when applied

Example.java


fruits = new String[5]

Will be: smile: The point to note here is the number of elements.

Isn't it 4 because the subscripts are from 0 to 4? : thinking: I think. It is different. Since it is the number of elements, it is the number of cardboard boxes. Because the numbers starting from 0 are assigned to each cardboard.

0 1 2 3 4

There are a total of 5 numbers, so the number in [] is 5: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits;
	    fruits = new String[5];
	}
}

So far, this is the summary, but you can shorten the code even further.

    1. Declaration of array variables
  1. Creating and assigning elements

This is a one-line method.

Lecture.


Mold[]Array variable name= new Mold[Element count]

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = new String[5];
	}
}

It's even easier to see: laughing:

Assign values to array elements and call values

A new shelf is also available. A new cardboard box is also available. Now let's finally put the fruit in the cardboard: smile:

Regarding how to put fruits, I think you mentioned that cardboard has a subscript (index). Use this subscript to add fruit to the cardboard: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = new String[5];
	    fruits[0] = "Apple";
	    System.out.println(fruits[0]);
	}
}

On the 4th line fruits [0] = "apple"; ("` Д´) "<Cardboard on the fruit shelf [0] Put an apple in the number! (Assign values to array elements)

In System.out.println (fruits [0]); on the 5th line ("` Д´) "<Check the contents of the cardboard box [0] on the fruit shelf! After confirming (calling the value)

console.


Apple

Is displayed: smile:

Now that I know how to insert and call elements, I'll write the code again: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = new String[5];
	    fruits[0] = "Apple";
	    fruits[1] = "Mandarin orange";
	    fruits[2] = "Strawberry";
	    fruits[3] = "melon";
	    fruits[4] = "banana";
	    
	    System.out.println(fruits[0]);
	    System.out.println(fruits[1]);
	    System.out.println(fruits[2]);
	    System.out.println(fruits[3]);
	    System.out.println(fruits[4]);
	}
}

The code is long! : scream: The array doesn't mean anything! : scream:

Just changing the writing style has made the situation very meaningless. Is there any way ...? : thinking:

Lecture.


1.Element type[]Array variable name= newElement type[] {Value 1,Value 2,Value 3,・ ・ ・}
2.Element type[]Array variable name= {Value 1,Value 2,Value 3,・ ・ ・}

There are two ways! : smile: With this formula alone, you can declare array variables, create elements, assign them, and assign values at the same time. ... Then, what was the explanation as it is ..., but if the value to be included in the element is decided, it is better to use this lecture: smile:

For example ...

int[5] number = new java.util.Random().nextInt(10);

In such a case. Put a random number from 0 to 9 among the five elements. At that time like the above lecture

  1. Element type [] Array variable name = new Element type [] {Value 1, Value 2, Value 3, ...}
  2. Element type [] Array variable name = {value 1, value 2, value 3, ...}

Then, I still don't know what number to put. In that case, the above lecture cannot be used.

int[] numbers = new int[5]

There is no choice but to create it as before.

Let's get back to the story ... I'll use 2 this time: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = {"Apple","Mandarin orange","Strawberry","melon","banana"};
	    
	    System.out.println(fruits[0]);
	    System.out.println(fruits[1]);
	    System.out.println(fruits[2]);
	    System.out.println(fruits[3]);
	    System.out.println(fruits[4]);
	}
}

The code is much shorter: raised_hands:

All that's left is the System.out.println part: laughing: From the result, use the for statement. However, since there is an explanation of length before using the for statement, I will explain the length first and then the for statement: smile:

Check the number of elements in the array

Well ... how many cardboard boxes were there on the fruit shelf? ?? : thinking: You may want to know the number of cardboard boxes.

At that time, I think you will ask the person who manages the actual warehouse. Similarly, you can ask your computer about the number of elements.

Lecture.


Array variable name.length

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = {"Apple","Mandarin orange","Strawberry","melon","banana"};
	    int number = fruits.length;
	    System.out.println("Cardboard on the fruit shelf" + number + "There are one!");
	}
}

On the 4th line, int number = fruits.length; fruits.length; asks for the number of elements (the number of cardboard boxes), so the type is int. Assign the number of elements to the variable number.

The number of elements is displayed on the 5th line.

console.


There are 5 cardboard boxes on the fruit shelf!

Arrays and for statements

Use of all elements by repetition (loop)

I also explained length, so use the for statement Let's shorten the code in System.out.println: laughing: The answer is: laughing:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = {"Apple","Mandarin orange","Strawberry","melon","banana"};
	    for (int count = 0; count < fruits.length; count++) {
	        System.out.println(fruits[count]);
	    }
	}
}

The count <fruits.length; part of the for statement on the 4th line fruits.length; represents the number of elements, so in this case it is 5. Since 0 is assigned as the initial value to the variable count Repeat until 0 <5 and the condition is met.

The part of fruits [count] on the 5th line is Since 0 is assigned as the initial value to the variable count Fruits [0] is called and the apples are printed. Because iterative processing is set up to 0 <5 Subscripts [0] to [4] are called and their values are output.

console.


Apple
Mandarin orange
Strawberry
melon
banana

By the way, if you change the part of int count = 0 on the 4th line to int count = 3 Since fruits [count] becomes fruits [3] and the subscripts [3] to [4] are called and output, the display is as follows: smile:

console.


melon
banana

With code like this, even if there are additional items, they will only be added on the third line, so it will be very easy to use: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = {"Apple","Mandarin orange","Strawberry","melon","banana","Kiwi"};
	    for (int count = 0; count < fruits.length; count++) {
	        System.out.println(fruits[count]);
	    }
	}
}

Add kiwi on the 3rd line

console.


Apple
Mandarin orange
Strawberry
melon
banana
Kiwi

Chan was displayed: laughing:

Using elements in order in this iterative process (loop) is called ** turning an array **: smile: The ceremony is below: smile:

Lecture.


for (int variable name= 0;Variable name<Array variable name.length;Variable name++)

If you just want to output the entire contents of the array, you can also use the ** extension for statement **: smile:

Lecture.


for (Element type variable:Array variable name)

Example.java


public class Main {
	public static void main(String[] args) {
	    String[] fruits = {"Apple","Mandarin orange","Strawberry","melon","banana","Kiwi"};
	    for (String count : fruits) {
	        System.out.println(count);
	    }
	}
}

Aggregation by repetition (loop)

You can also use this iterative process to sum the elements: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    int[] numbers = {10,20,30,40,50};
	    int sum = 0;
	    for (int count = 0; count < numbers.length; count++) {
	        sum += numbers[count];
	    }
	    System.out.println(sum);
	}
}

However, int sum = 0; on the 4th line, but since the value must be assigned and initialized before fetching the value of the variable, 0 is assigned to the variable sum as int sum = 0 ;.

If you quantify sum + = numbers [count]; on the 6th line 0 += 10 That is, it calculates 0 + 10 and assigns the answer to the variable sum. It is repeated, 10 + 20 ... 20 + 30 ..., and the result of summing all the elements is

console.


150

Will be: smile:

By the way, how many numbers are over 30 using the if statement? You can also say: smile:

Example.java


public class Main {
	public static void main(String[] args) {
	    int[] numbers = {10,20,30,40,50};
	    int conditions = 0;
	    for (int count = 0; count < numbers.length; count++) {
	        if (numbers[count] >= 30) {
	            conditions++;
	        }
	    }
	    System.out.println(conditions);
	}
}

console.


3

Use of information corresponding to subscripts

int variable = new java.util.Random (). nextInt (3); The above is an expression that assigns a random number from 0 to 2 to a variable. Integers can be displayed randomly, but what if you want the characters to be displayed randomly? : thinking:

Example.java


public class Main {
	public static void main(String[] args) {
	    
	    int[] word = new int[5];
	    
	    for (int number = 0; number < word.length; number++) {
	        word[number] = new java.util.Random().nextInt(3);
	    }
	    
	    for (int number = 0; number < word.length; number++) {
	        switch (word[number]) {
	            case 0:
	                System.out.println("duck");
	                break;
	            case 1:
	                System.out.println("Cherry Blossoms");
	                break;
                case 2:
                    System.out.println("Acorn");
	                break;
	        }
	    }
	}
}

You can use a switch statement like this: smile:

Prepare a new shelf and 5 new cardboard boxes with int [] word = new int [5]; on the 3rd line.

The meaning of the for statement on the 4th to 6th lines is to substitute the randomly picked numbers from 0 to 2 into word [number].

The meaning of the for statement on the 7th to 18th lines is to find the number stored in word [number] from the switch statement, and if it matches the same number, output the character written there. (If word [0], the duck of case 0 is output)

console.


Acorn
duck
Cherry Blossoms
Cherry Blossoms
Acorn

Recommended Posts

[Java] array
Java array
Java array
java (array)
Java array
[Java] Array
Java array
java array
[Java] Array
java array variable
[Java] Array notes
About Java Array List
Java
[Java ~ Array ~] Study memo 4
Java
Array
[Java] List type / Array type conversion
Java Development Basics ~ Exercise (Array) ~
[Java] Convert ArrayList to array
[Java Silver] Array generation method
How to initialize Java array
[Beginner] Java basic "array" description
Java learning (0)
Studying Java ―― 3
Java protected
[Java] Annotation
[Java] Module
[Ruby] Array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Array practice
Java methods
Java method
java (constructor)
[Java] ArrayDeque
java (override)
java (method)
Java string
Java learning memo (creating an array)
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Studying Java ―― 1
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features