Array definition • Loop operation __java

Source: Internet
Author: User
Tags array definition array length
what is an array

Q: Write code to save 4 students ' exam results.

A: Simple ah, define 4 variables Bai

Q: "Calculate the test scores of 400 students in the whole year", what's the swelling?

For:.......

array , it can help you solve the problem properly.

An array can be understood as a huge "box" in which multiple types of data can be stored sequentially, for example, an array of int can be defined scores store 4 students ' scores

Elements in an array can be accessed by subscript, starting with the subscript 0. For example, you can get the first element in an array by scores[0], scores[2] You can take the third element 92. Task

The happy practice time again.

An array scores is defined in the editor to hold the test scores for five students, please complete the code in line 8 and output The second result in the array

The result of the run is: the 2nd score in the array is:

public class HelloWorld {public
    static void Main (string[] args) {

		//define an array, save five students ' scores
		int[] scores = {78, 93 , the ",", "the";

		The second result in the output array
		System.out.println (the 2nd result in the array is: "+scores[1]);
	}



How to use an array in Java

The operation array in Java requires only four steps:

1. Declaring an array

Syntax: data type [] array name;

or data type array name [];

Where the array name can be any valid variable name, such as:

2. Allocate Space

To put it simply, you specify how many elements can be stored in an array

Syntax: array name = new data type [array length];

The length of the array is the number of elements that can be stored in an array, such as:

In other words, we can also combine the two steps above to allocate space for it when declaring an array, such as:

3. Assigning Value

After allocating space, you can put data into the array, and the elements in the array are accessed by subscript, such as storing student scores in a scores array

4, processing the data in the array

We can manipulate and process the assigned array, such as getting and outputting the values of the elements in the array.

Another way to create an array directly in Java is to declare an array, allocate space, and assign a merge complete, as

It is equivalent to:

Task

Small partners, the use of the array of steps you have mastered it, let's examine it.

An array subjects is defined in the editor to hold the test account information, please complete the code in line 5, and output the fourth account information in the array.

The result is: the first 4 accounts in the array are: Java

public class HelloWorld {public
    static void Main (string[] args) {
        
		//define a string array of length 5, save the test account information
		string[] subjects = new string[5]                   ;
        
		Assign values to the elements in an array
		subjects[0] = Oracle;
		SUBJECTS[1] = "PHP";
		SUBJECTS[2] = "Linux";
		SUBJECTS[3] = "Java";
		SUBJECTS[4] = "HTML";
        
		System.out.println (the first 4 accounts in the array is: "+ subjects[3]          );
	}
<span style= "font-family: Microsoft Yahei"; font-size:16px; line-height:30px; Background-color:rgb (236, 238, 240); > Single Exercises </span>
The following array is initialized correctly () aint[] score = new int[]; Bint score[] = new int[] {34, 90, 87, 54, 24}; Cint[] score = new Int[4] {90, 12, 34, 77}; Dint score = {78, 23, 44, 78};
parsingOption A needs to specify the length of the array; option C cannot specify the length of the array when assigning values while declaring the array; option D declares the syntax error of the array, which should be int[] score={78, 23, 44, 78}; so select B

using loops to manipulate arrays in Java

In actual development we often use loops to control the operation of array members. Such as:

Run Result:

Where the array name. Length is used to get the length of the array

"Minor problems" to note:

1, the array subscript starting from 0 . So Scores[3] represents the 4th element in the array, not the 3rd element

2, the range of the array subscript is 0 to the array length-1 , if the Cross-border access, it will be an error. Such as:

The runtime will report the following error:

The error message above means that the array subscript exceeds the range, that is, the array accesses the bounds. In the above code, create an array of length 2, so the array subscript range is 0 to 1, and the program subscript 2, that is, scores[2], exceeds the range, causing array access to cross bounds. Task

Complete the code in the editor at line 9 , to achieve the output of the array elements

Run Result:

public class HelloWorld {public
    static void Main (string[] args) {
		
		//define a string array of length 3 and assign the initial value
		string[] Hobbys = {"Sports", "Game", "movie"};
		System.out.println ("The value of the element in the loop output array:");
		
		Use loops to iterate through the elements in the array for
		(int i=0;i
Programming Exercises

Small partners, according to the knowledge, reference notes, in the Code Editor to supplement the code, complete the JAVA program, the output array to achieve the maximum, minimum and average value

Operation Effect:

Task

Mission Requirements:

1, define an integer array, and assign the initial value 61, 23, 4, 74, 13, 148, 20

2, define variables to save the maximum, minimum, cumulative and average, and assume that the first element in the array is both the maximum and the minimum value

3. Use a For loop to iterate through the elements in the array, comparing them to the assumed maximum and minimum values. Replaces the current maximum if it is larger than the assumed maximum value, and replaces the current minimum if it is smaller than the assumed minimum value

4, the cycle of the implementation of the elements of the array to sum up

5

public class HelloWorld {public
    
    static void Main (string[] args) {
        
		//define an integer array and assign an initial value
		int[] nums = new int[] {6 1, 4, 148, N;
        
		int max = nums[0]; Assuming the maximum value is the first element of the array
		int min = nums[0];//Suppose the minimum value of the first element in the array is
		double = 0;//additive
		Double avg = 0;//mean
        
		value for ( int i = 0; i < nums.length; i++) {//looping through the elements in the array
        //If the current value is greater than Max, replace the value of Max if
		(Nums[i]>max)
            max=nums[i];
        
        
        If the current value is less than min, replace min's value
        if (nums[i]<min)
            min=nums[i];
        
        
        
        Cumulative sum
        sum+=nums[i];
        
		}
        
        To find the average
       
        avg=sum/nums.length;
		SYSTEM.OUT.PRINTLN ("Maximum value in array: + Max");
		System.out.println ("The smallest value in the array:" + min);
		System.out.println (average in array: + avg);
	}

, the loop end calculates the average based on the cumulative value, and prints out the relevant content


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.