Java Experiment 2: Array & Enhanced for Loop

Question 1: 36 generates 7

It means: Given an array of size 7, each element of the array is required to be different from each other, random numbers distributed in [1, 36], and the array is output using an enhanced for loop.

My solution:

import java.math.*;

@SuppressWarnings("unused")
public class Main3 {
    
    
	public static void main(String[] args) {
    
    
		int[] ele = new int[7];
		for(int i = 0;i < ele.length;++i) {
    
    
			Here:
			while(true) {
    
    
				int Temp = (int)(Math.random() * 36.0) + 1;
				for(int j = 0;j < i;++j)
					if(Temp == ele[j])
						continue Here;
				ele[i] = Temp;
				break;
			}
		}
		for(int num : ele)
			System.out.print(num + " ");
	}
}

Summary of the use of knowledge points:

First: Array is a reference data type

Array is a reference data type. The so-called reference data type means that each element of the array is actually just an address (placed as a variable in the stack area), and this address points to an object entity (the entity is placed in the heap area). Then no matter what kind of data type we declare, we use new to declare dynamically, but the initialization can be dynamic or static. If the array declared in this way is not assigned an initial value, it follows the rule: if it is an array of ordinary data type, it is initialized to 0, and an array of object data type is initialized to NULL.

Second: traversal of the array

Because the array is a reference type, it means that the array itself is also an object, so the attributes of the array not only have the element value of the array (pointing to the address of the entity), but also other attributes, such as length! This attribute is very useful. When the array is declared, the attribute value length is automatically initialized according to how much space is opened up when the array is declared.
Then when traversing, you can use the attribute length as the number of loops!

Third: enhance the for loop

Java has introduced an enhanced for loop. The disadvantage of such a for loop is that only read operations can be performed in this for loop, and cannot be written, which means that the for loop can only output data but cannot access and modify it. ! The syntax format is:

for(Type ele : array)
	System.out.println(ele);

Note that this ele is the value of the traversal array, and the output is also ele, not array[ele]! !

Fourth: replace the goto statement of c++ with a label after continue!

In the above code, we use the form of adding a label after continue. This label must be declared first, indicating the position that needs to be reached after meeting the condition of continue! It is obvious here that we need to re-enter the loop when we have encountered a duplicate value, so our label is placed in the signature of the loop, pay attention to the colon after the declaration label !

Guess you like

Origin blog.csdn.net/qq_44274276/article/details/104816440