[For beginners] Introduction to Java Basic knowledge of Java language ③ Array, selection structure, iteration structure

Part 3 We will explain the basic knowledge for Java beginners. If you haven't seen it yet, please take a look at the past articles ↓ "[For beginners] Introduction to Java: Basic knowledge of Java language ①" "[For beginners] Introduction to Java Basic knowledge of Java language (2) Identifiers, variables, operators" This time, I will explain the control statements and arrays in Java that handle the selection structure and iterative structure, which are the basic structures of the algorithm.

Array

A data structure for handling a group of variables of the same type as a group is called an array. This is convenient when you want to use multiple basic data types and String types at once. For example, when using 30 values in a program, it is necessary to declare 30 times for variables, but for arrays, it is possible to secure an area and use values with one declaration. The number of values stored in the array is called the number of elements. Element numbers are assigned to the number of elements to identify them individually, and the element numbers start from 0. To use an array, you need to specify the array name and the number of elements. 配列.jpg The format and example are as follows.

1. Array variable declaration </ b> </ span> </ b>

Type name [] array name; or type name array name []; </ code> Example: Define a numeric number array int[] numbers;

2. Reserve array area </ b> </ span>

Array name = new Type name [number of elements]; </ code> Example: Define a numeric number array with 5 elements numbers= new int[5];

Example of performing 3.1 and 2 at the same time </ b> </ span>

int[]a = new int[5]

4. Assign to array elements </ b> </ span>

Array name [element number] = value; </ code> Example: Assign 11 to the 0th of the numbers array numbers[0]=11;

5. Array variable declaration, area allocation, and array initialization are performed at the same time </ b> </ span>

Type name [] Array name = {Initial value 1, Initial value 2 ...}; </ code> Example: Create a numeric ages array and initialize it with 11,22,33,44 int []ages = {11,22,33,44};

Selection structure

A structure that branches processing according to conditions and executes it is called a selection structure.

For example, if the probability of precipitation is 50% or more, bring an umbrella, if it is less than 50%, 30% or more, bring a folding umbrella, and at other times, take nothing. .. At this time, the processing branches depending on the probability of precipitation of 50% or more, 50% or more and less than 30%, and other times, and different processing is performed depending on each condition. 選択.jpg

Selection structure control statement ① IF-else statement

The IF-else statement is one of the control statements of the selection structure that makes two branches depending on whether the result of the conditional expression is true or false. Conditional expressions are calculated using relational operations and logical operations. You can also create a multi-branch structure by using IF-else statements consecutively, but be aware that creating a multi-branch structure will reduce readability. The format is as follows.

1. if-else only </ b> </ span>

If the conditional expression is correct, process 1 is performed, and if it is incorrect, process 2 is performed.

if(Conditional expression)
Process 1;
}else{
Process 2;
}

2.if-else if-else

If conditional expression 1 is correct, process 1 is performed, if conditional expression 1 is incorrect and conditional expression 2 is correct, process 2 is performed, and if neither conditional expression 1 nor conditional expression 2 is correct, process 3 is performed.

if(Conditional expression 1){
Process 1;
}else if(Conditional expression 2){
Process 2;
} else{
Process 3;
}

Example: Branch processing according to age

int age = 25; //Declare an age variable and set 25 as the initial value
if(age < 18) {//Underage output if age is under 18
     System.out.println("Minors");
}
else if(age >= 60){ //Elderly output when the age is 60 years old or older
     System.out.println("Senior citizens");
}else{//Adult output if not under 18 or over 60
     System.out.println("Adult");
}
  • In this example, the age is 25, so the adult is output.

Conditional branch ② switch-case statement

It is a control structure that performs multiple branches based on the value of the expression. Describe the value in the case statement and determine if the expression and value are equal. If none of the values match, the process described in default is executed. Break; is always required after the case statement, and if break; is not described, even if it matches, the switch statement will not be exited and processing will be performed more than necessary. Since multiple processing branches can be performed with one switch statement, it is easy to write a program. However, the Java switch-case statement has a limitation that the range of values cannot be specified. The format is as follows.

switch(formula){
case value 1:
Processing (when the content of the expression matches the value 1);
     break; //Get out of the switch statement.
case value 2:
Processing (when the contents of the expression and the value 2 match);
     break;
  default:
Processing (when the contents of the expression do not match any value);
}

Example: Output the result using the switchi statement based on the grade.

char rank = 'A'; //rank(Grades)Declare a variable and initialize it with ‘A’

String result; //result(result)Declare a variable
//Determine variable rank
switch(rank){
    case 'A': //If rank is A
       result = "Yu"; //結果にYuを入れる。
       break;
    case 'B': //When rank is B
       result = "Good"; //結果にGoodを入れる。
       break;
    case 'C': //If rank is C
       result = "Yes";
       break;
    default: //A place that is neither A nor B nor C
       result = "Impossible"; //結果にImpossibleを入れる。
}
System.out.println("Result is" + result + "is.");//Yu outputs.

Iterative structure

The specified process is repeated as long as the set conditions are met during the process. For example, if you have a person who does 300 sit-ups a day, that person repeats the sit-ups until 300 sit-ups and trains the sit-ups until 300 sit-ups. 反復.jpg

Iterative structure control statement ① (while statement)

It is an iterative structure that repeats the same process while the conditions are met. The process is executed after the condition is judged. The process is not executed once while the conditional expression is not satisfied. The format and example are as follows. In the example, standard input is used, but now it's okay to just enter the password from the keyboard.

while(Conditional expression){
processing
}

Example: Repeat until passwords match

int hantei=0
String password;
while( hantei != 999 ){ //Judgment 999 = Repeat until password matches
    System.out.println("Please enter your password.");
    Scanner sc = new Scanner(System.in);//Enter characters from the keyboard
    password = sc.next() //Pass the entered characters to the password.
    if(password == “99999”){//Confirm the entered characters and password.
       hantei =999; //If they are equal, put 999 in the judgment and exit repeatedly
       System.out.println("Login successful");
    else{
       System.out.println("Login failure")
    }
}

Iterative structure control statement (2) (do-while statement)

The while statement was a statement that executes processing after performing condition judgment, but the do-while statement executes processing first and then performs condition judgment. The format and example are as follows.

do{
processing;
}

while(Conditional expression);

Example: Repeat until 1 is entered

int number;
do{
    System.out.println("If you enter 1, you can exit repeatedly.");
    Scanner sc = new Scanner(System.in);
    number = sc.nextInt();
}while(number !=1); //Repeat while number is not 1.

Iterative structure control statement ③ (for statement)

The for statement is an iterative structure that repeats the same process until the counter variable set in the initial expression satisfies the conditional expression. A variable that counts the number of repetitions is called a counter variable. In the initial setting, the initial value is set, in the conditional expression, the continuation condition is set, and in the expression, the processing to be performed each time the iterative processing occurs is set. A; (semicolon) is required to separate the initial settings, conditional expressions, and expressions.

for(Initial setting;Conditional expression;formula){
processing;
}

Example Output the number of repetitions.

for( int i=1 ; i<4 ; i++ ){ //i starts from 1 and increases by 1 and repeats for less than 4
    System.out.println(i+"Times"); //1Times、2Times、3Timesと表示される。
}
  • Of the for statement and the while statement, the for statement is used more frequently, and the while statement has a fixed number of repetitions, and the for statement has a fixed number of repetitions.

Iterative structure ④ Extended for statement The extended for statement is a syntax for iterating over a set of elements such as an array. Iterate while referring to the elements in order from the beginning to the end. It is easy to describe because there is no need to set initial values or formulas. The format and example are as follows.

Format

for(Variable declaration:Array name){
processing
}

Example: Output all elements of the numbers array.

int numbers[] = {1,2,3,4,5};
for(int number:numbers){
    System.out.println(number);
}

Example of combining array, extended for statement and if statement 1.PNG

An example of using a for statement inside a for statement 2.PNG

Summary

Array data structure of a collection of variables of the same type

With an array, it is possible to allocate space and use values with a single declaration.

In order to use an array, it is necessary to specify the array name and the number of elements.

Select the structure to branch the process according to the condition and execute it.

Specify a range in the selection structure and use branch = if-else statement, multi-branch = switch statement

Iterative structure that repeats the specified process while satisfying the conditions set in the middle of the process

Use a for statement with a fixed number of iterations and an indefinite number of iterations = while statement

This time is over. Thank you for reading to the end. Next time, I will finally explain object-oriented programming.

Recommended Posts