What I learned in Java (Part 4) Conditional branching and repetition

Looking back on Java

Last time, I wrote about instruction execution statements in Java. Please see that if you like. What I learned in Java (3) Instruction execution statement

This time I would like to write about conditional branching and repetition.

What is conditional branching?

A Java program consists of a control structure of "rank", "branch", and "repetition". Java is processed in order from the top of the source code. This is called "sequential".

public class Main {
	public static void main(String[] args) {
		int a = 1;
		int b = 2;
		int c = a + b;
		System.out.println(c);
	}
}

Execution result スクリーンショット 2020-11-09 140016.png In addition to proceeding "sequentially" as described above, I think it will branch in some cases. For example, if you have trouble with rice or bread at breakfast ... スクリーンショット 2020-11-10 120212.png This kind of branching is called "branching". I would like to actually write the source code

public class Main {
	public static void main(String[] args) {
		//Ask them to choose between rice and bread
		System.out.println("What do you eat for breakfast?");
		System.out.println("Enter "0" for rice and "1" for bread");
		int morning = new java.util.Scanner(System.in).nextInt();
		
		//If it was rice
		if (morning == 0) {
			System.out.println("Prepare rice, miso soup and side dishes ...");
		
		//If it was bread
		} else {
			System.out.println("Bake in a toaster, butter, ...");
		}
		
		System.out.println("I will!");
	}
}

Execution result

if (morning == 0) {
    System.out.println("Prepare rice, miso soup and side dishes ...");	
} else {
    System.out.println("Bake in a toaster, butter, ...");
}

This part is called an if statement. When translated into human language "If breakfast is rice, prepare rice, miso soup, and side dishes." "Else (otherwise) bake bread and butter" It is the content. You can "branch" by using the if statement like this.

What is repetition

Next, I would like to compare "repetition" with the distance to the destination. スクリーンショット 2020-11-10 141609.png Let's write the above contents in source code.

public class Main {
	public static void main(String[] args) {
		//Number of steps to the destination (this time the vending machine)
		int destination = 10;
		System.out.println(destination + "Let's buy juice from the vending machine at the destination!");
		//Number of steps taken
		int steps = 0;
		
		//Repeat until you reach your destination
		while (steps != destination) {
			System.out.println("Take a step forward");
			steps++;
		}
		System.out.println("I arrived at the vending machine, so I bought juice");
	}
}

Execution result スクリーンショット 2020-11-10 142932.png I implemented the above code by walking "repeatedly" until I arrived at the vending machine 10 steps away!

The part that is actually repeated is as follows.

//Number of steps to the destination (this time the vending machine)
int destination = 10;
//Number of steps taken
int steps = 0;		
//Repeat until you reach your destination
while (steps != destination) {
    System.out.println("Take a step forward");
    steps++;
}

It is an image of going step by step to the destination (destination)! On the contrary, if the destination is set to 0 and it is corrected so that it does not approach.

//Number of steps to the destination (this time the vending machine)
int destination = 0;
//Number of steps taken
int steps = 10;		
//Repeat until you reach your destination
while (steps != destination) {
    System.out.println("one step closer");
    steps--;
}

It doesn't change that much, but ... In this way, the while statement is iteratively processed as long as the condition is met.

How to write if statement and while statement

Statements that represent control structures, such as if statements and while statements, are called control syntax. I would like to summarize how to write it below.

//if statement
if (Conditional expression) {
Processing performed when the condition is met
} else {
Processing performed when the conditions are different
}

//while statement
while (Conditional expression) {
Processing performed when the condition is met
}

Conditional expressions are expressions used in if statements and while statements to express "conditions for branching processing" and "conditions for continuing repetition".

//If the variable number is 0
if (number == 0) {}
//You were if the variable s is "Hello"
if (s.equals("Hello")) {}

//If the variable number is 20 or more
while (number >= 20) {}

The "==" and "> =" in the conditional expression are called relational operators. Types and meanings of relational operators

operator meaning
== Left side and right side are equal
!= The left side and the right side are different
> The left side is larger than the right side
< The left side is smaller than the right side
>= Left side is greater than or equal to right side
<= Left side is less than or equal to right side
.equals() Strings are equal()Fill in the comparison target
//Age 20+ and 65+
if (age >= 20 && age <= 65) {}
//30 years or younger or male
if (age <= 30 || gender == 0 ) {}

"" in the conditional expression&&」「||Is called a logical operator. Types and meanings of logical operators

operator meaning
&& And (if both conditions are met)
|| Or (if only one of the conditions is met)

Other branch syntax and repeat syntax variations

if statement only syntax

if (Conditional expression) {
Processing performed when the condition is met
}

Since there is no else statement, nothing is done if the conditional expression does not apply.

if-else if-else syntax

if (Conditional expression 1) {
Processing performed when the condition is met
} else if (Conditional expression 2) {
Processing performed when the condition is met
} else if (Conditional expression 3) {
Processing performed when the condition is met
} else {
What happens if the condition is not met
}

One if statement can branch to three or more routes.

switch syntax

switch(Condition value)
case value 1:
Process 1
        break;
case value 2:
Process 2
        break;
case value 3:
Process 3
        break;
    default:
Process 4

switch statement Conditions that can be used (1) An expression that compares whether conditional expressions match, such as "variable == value" and "variable == variable". (2) The value to be compared is an integer, a character string, or a character, not a decimal value or a boolean value.

do-while syntax

do{
block
} while (Conditional expression)

The while statement first determines the conditional expression (pre-judgment), and if the condition is met, the processing inside the block is executed. The do-while statement judges the conditional expression (postfix judgment) after the processing in the block is performed.

for statement

for (int i = 0; i < 10; i++){
Repeated processing
};

The process is repeated the number of times the int type i increases from "0" to "10" (i ++ part).

Control structure nesting

Conditional branches and repetitive statements (control structures) can be placed in different control structures. This is called "nesting" or "nesting". A simple multiplication table example ...

for (int i = 1; i < 10; i++){
	for (int j = 1; j < 10; j++) {
		System.out.print(i * j);
		System.out.print(" ");
	}
	System.out.println("");
}

Execution result スクリーンショット 2020-11-11 121241.png I think that you can play various if statements, while statements, for statements, etc. depending on how you use them, so please try them!

References

https://book.impress.co.jp/books/1113101090

Next time, I would like to write about arrays.

Recommended Posts

What I learned in Java (Part 4) Conditional branching and repetition
What I have learned in Java (Part 1) Java development flow and overview
What I learned in Java (Part 2) What are variables?
java (conditional branching and repetition)
What I learned in Java (Part 3) Instruction execution statement
What I learned when building a server in Java
What I learned with Java Gold
What I learned with Java Silver
[Note] What I learned in half a year from inexperienced (Java) (1)
[Note] What I learned in half a year from inexperienced (Java) (3)
What I learned from Java monetary calculation
What i learned
Let's think about what declarative programming is in Java and Elm (Part 1)
Summary of what I learned in Spring Batch
What I learned ② ~ Mock ~
What I learned ① ~ DJUnit ~
I tried Mastodon's Toot and Streaming API in Java
A quick review of Java learned in class part4
Calendar implementation and conditional branching in Rails Gem simple calendar
A quick review of Java learned in class part3
[Rilas] What I learned in implementing the pagination function.
A quick review of Java learned in class part2
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapters 4 and 5
I tried to find out what changed in Java 9
What I researched about Java 8
JSON in Java and Jackson Part 1 Return JSON from the server
Java conditional branching: How to create and study switch statements
What I researched about Java 6
I made roulette in Java.
Java and Iterator Part 1 External Iterator
What I researched about Java 9
Apache Hadoop and Java 9 (Part 1)
What happened in "Java 8 to Java 11" and how to build an environment
What I researched about Java 7
What you learned when you acquired Java SE 8 Silver and Gold
I tried metaprogramming in Java
I want to simplify the conditional if-else statement in Java
What I learned about Kotlin
What I researched about Java 5
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 10)
[java] What I did when comparing Lists in my own class
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 7)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 3)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 9)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 6)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 4)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 5)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 2)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 1)
What I learned from doing Java work with Visual Studio Code
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 11)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 12)
Summary of "Design Patterns Learned in Java Language (Multithread Edition)" (Part 8)
Basics of conditional branching and return
I sent an email in Java
I compared PHP and Java constructors
I created a PDF in Java.
Encoding and Decoding example in Java
I wrote Goldbach's theorem in java
StringBuffer and StringBuilder Class in Java
[Java] What got caught in encapsulation