[Studying Java Core] #4

Inwook Baek ·2021년 10월 5일
0

Java Study

목록 보기
4/6
post-thumbnail

The while and do-while loops

The while loop

The while loop consists of a block of code and a condition (a Boolean expression). If the condition is true, the code within the block is executed. This code repeats until the condition becomes false. Since this loop checks the condition before the block is executed, the control structure is also known as a pre-test loop. You can think of the while loop as a repetitive conditional statement.

while (condition) {
    // body: do something repetitive
}
public class WhileDemo {

    public static void main(String[] args) {
        char letter = 'A';
        while (letter <= 'Z') {
            System.out.print(letter);
            letter++;
        }
    }
}

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

The do-while loop

In the do-while loop, the body is executed first, while the condition is tested afterward. If the condition is true, statements within the block are executed again. This repeats until the condition becomes false. Because do-while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. In contrast to the while loop, which tests the condition before the code within the block is executed, the do-while loop is an exit-condition loop. So, the code within the block is always executed at least once.

do {
    // body: do something
} while (condition);

A good example of using it is a program that reads data from the standard input until a user enters a certain number or string. The following program reads integer numbers from the standard input and displays them. If the number 0 is entered, the program prints it and then stops. The following example demonstrates the do-while loop:

public class DoWhileDemo {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int value;
        do {
            value = scanner.nextInt();
            System.out.println(value);
        } while (value != 0);
    }
}

Input

1 2 4 0 3

Output

1
2
4
0
Scanner scanner = new Scanner(System.in);

int sum = 0;
while (scanner.hasNext()) {
    int elem = scanner.nextInt();
    sum += elem;
}

System.out.println(sum);

Example 1:
Find the sum of all elements of a sequence, ending with the number 0.

The number 0 itself is not included into the sequence and serves as a sign of cessation.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int sum = 0;
        
        while (sc.hasNext()) {
            int elem = sc.nextInt();
            if (elem == 0) {
                break;
            } else {
                sum += elem;    
            }
        }
        System.out.print(sum);
    }
}

Input

3
6
8
0

Output

17

Example 2:
Ann puts MM money in the bank. The bank increases Ann's deposit by PP percent every year. Ann wants to know how many years should pass until her deposit in the bank reaches KK money. Can you help her to answer this question?

The input contains three integers M, P, KM,P,K. It is guaranteed that all numbers are positive and K \geq MK≥M.
Output the answer to Ann's question.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        double m = sc.nextInt();
        double p = sc.nextInt();
        int k = sc.nextInt();

        sc.close();
        
        int t = 0;
            
        while (k > m) {
            m += m * (1 * p / 100);  
            t++;       
        }
        System.out.print(t); 
    }
}

Input

100 15 120

Output

2

Branching Statements

Branching statements are used to alter the standard behavior of loops; they can terminate a loop or skip some iterations.

The break statement

int i = 10;
while (true) { // the condition to continue the loop
    if (i == 0) { // the condition to perform the break that stops this loop 
        break;
    }
    i--;
}

The break statement terminates only the loop in which it is currently located. If this loop is performed inside another loop, the outer loop won't be stopped.

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        System.out.print(j + " ");
        if (i == j) {
            break;
        }
    }
    System.out.println();
}

Output:

0 
0 1 
0 1 2 
0 1 2 3 
0 1 2 3 4 
0 1 2 3 4 5 
0 1 2 3 4 5 6 
0 1 2 3 4 5 6 7 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 9 

To stop the outer loop we'd like to declare a Boolean variable stopped and use it as a special Boolean flag.

boolean stopped = false;
for (int i = 0; (i < 10) && !stopped; i++) {
    for (int j = 0; j < 10; j++) {
        System.out.print(j + " ");
        if (i == j) {
            stopped = true;
            break;
        }
     }
    System.out.println();
}

Output:

0

The continue statement

It causes a loop to skip the current iteration and go to the next one.

This statement can be used inside any kind of loops.

  1. Inside the for-loop, the continue causes control to immediately move to the increment/decrement statement;
  2. Inside the while or do-while loop, control immediately moves to the condition.

In the following example, a sequence of numbers is output. Odd numbers are skipped.

int n = 10;
for (int i = 0; i < n; i++) {
    if (i % 2 != 0) {
        continue;
    }
    System.out.print(i + " ");
}

Output:

0 2 4 6 8

Example 1:
Given a sequence of natural numbers. For each number of the sequence output "even" if the number is even, otherwise, "odd". If the number is equal to 0, the program must stop reading and processing numbers.

import java.util.Scanner; 

public class jetBrains_EvenOrOdd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNext()) {
            int n = sc.nextInt(); 
            if (n == 0) {
                break;
            } else if (n % 2 == 0) {
                System.out.println("even");
            } else {
                System.out.println("odd");
            }
        }
    }
}

Input

1
2
3
4
0

Output

odd
even
odd
even

Example 2:
Write a program that reads a sequence of integer numbers in a loop and adds up all numbers.

If a new number is equal to 0, the program must stop the loop and output the accumulated sum.

When the sum is equal to or exceeds 1000 (the barrier), the program should also stop and output the value equal to sum minus 1000 (sum – 1000).

Note: the input can contain extra numbers. Just ignore them.

import java.util.Scanner; 

public class jetBrains_TheInteger {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int sum = 0;
        int exceed = 0;
        
        while (sc.hasNext()) {
            int n = sc.nextInt(); 
            if (n == 0) {
                if (sum >= 1000) {
                    exceed = 1000;
                }
                break;
            } else if (sum >= 1000) {
                exceed = 1000;
            } else if (n >= 1000) {
                exceed = 1000;
                sum += n;
            } else {
                sum += n;
            }
        }
        sum -= exceed; 
        System.out.print(sum);
    }
}

Input

103
105
109
0
1000

Output

317

Switch Statement

Three keywords: switch, case, and default

The switch statement provides a way to choose between multiple cases based on the value of a single variable (not an expression!). The variable can be an integer number, character, string, or enumeration. The last two types will be studied further.

switch (variable) {
    case value1:
        // do something here
        break;
    case value2:
        // do something here
        break;
    
    //... other cases
    
    case valueN:
        // do something here
        break;
    default:
        // do something by default
        break; // it can be omitted
}

Example:
Harry Potter needs help identifying what each house means.

Read a string representing a house and output the following:

if it is "gryffindor", output "bravery";
if it is "hufflepuff", output "loyalty";
if it is "slytherin", output "cunning";
if it is "ravenclaw", output "intellect";
otherwise, output "not a valid house".

import java.util.Scanner;

public class jetBrains_HarryPotter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String name = sc.next(); 
        
        switch (name) {
            case "gryffindor":
                System.out.print("bravery");
                break;
            case "hufflepuff":
                System.out.print("loyalty");
                break;
            case "slytherin":
                System.out.print("cunning");
                break;
            case "ravenclaw":
                System.out.print("intellect");
                break;
            default: 
                System.out.print("not a valid house");        
                break;        
        }  
    }
}

Input

gryffindor

Output

bravery

Calling a Method

Each method has a name that is used to call it. Generally, it reflects what the method does – prints, finds, calculates, provides you with some information.

The Java compiler requires a method name to be a legal identifier. The rules for legal identifiers are the following:

  1. Identifiers are case-sensitive;
  2. An identifier can include Unicode letters, digits, underscore _ or currency characters, such as $;
  3. An identifier can't start with a digit;
  4. Identifiers must not be a keyword.
  5. In addition, there is a naming convention that restricts possible method names. It's optional but desired for developers. By convention, a one-word name should be a verb in lowercase: sum, multiply, or round.

If a method has a multi-word name, the first letter of the second and the following words should be capitalized: getValue, calculateNumberOfOranges, or findLetter.

Declaring a Method

Built-in methods are a real deal when you manage routine tasks. Still, they are not a cure-all solution since it's impossible to provide a standard method for each specific task. For example, you may need to convert dollars to euros, count your monthly spendings, or even calculate a daily portion of seeds for your parrot multiple times. That's when you create your own method to avoid repeating tons of code!

In contrast to built-in methods, user-defined methods are created by the programmer. It is a common practice to create a customized subprogram for a specific purpose.

The syntax of the method

Technically, a method is just a structured part of code with a few components. In Java, a method is always located inside a class. Let's take a closer look at a method that calculates a daily portion of seeds for a parrot:

A method contains a set of modifiers, a type of the return value, a name, a list of parameters in parentheses () , and a body in curly brackets {}. The combination of the name of the method and the list of its parameters is known as a method signature. In our example, the signature is countSeeds(int, int).

Some methods also have a list of exceptions – they define its behavior in case of some mistake in the program. For now, we'll consider simple methods without exceptions.

Modifiers

The first words are so-called modifiers. There are two types of modifiers in Java: access modifiers and non-access modifiers.

Access modifiers define the visibility of the method. For now, we're using a public access modifier, which means there are no restrictions for invoking the method even from other classes.

Non-access modifiers provide information about the behavior of methods to JVM. The modifier static means that the method belongs to the class and it can be accessed without creating any object. This type of method is called a static method.

If the method is declared without the static modifier, it means that the method can be invoked only through or with an object or instance of this class. Such methods are called instance methods.

Example:
To perform math division, you have the method named divide that takes two long numbers and returns a double value.

Write a body of the method. It should return the result of the division of the first argument by the second one. It's guaranteed that the second argument is not equal to zero.

import java.util.Scanner;

public class Main {

    public static double divide(long a, long b) {
        return (double) a / b;
    }

    /* Do not change code below */
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final long a = scanner.nextLong();
        final long b = scanner.nextLong();
        System.out.println(divide(a, b));
    }
}

Input

500000000000 200000000000

Output

2.5

The Main Method

Java is primarily an object-oriented language. It means a Java program can be considered as a collection of objects that communicate via calling each other's methods. A typical Java program includes a lot of classes, interfaces, objects and other concepts from the object-oriented programming.

Even the simplest "procedural-style" program should have at least one class and the main method inside to start the program. The main method is the entry point for any application. Ever since Java 7 there has been no other way to start an application without this method (excluding the case when you start your application inside a special container for applications but it is not considered in our materials).

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello, Java");
    }
}

0개의 댓글