Xuanzi Java Basic Notes 2

User interaction

Basic Scanner

package CH02_JAVAProcessControl;
//Basic Scanner

import java.util.Scanner;

//Guide package
public class XZ01_UserInteraction {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
//Create a Scanner object
        System.out.println("Please enter 1");
        if (input.hasNext()) {
//            Determine whether the user enters data
            String i = input.next();
//            Declare variables to receive user input data
            System.out.println(i);
//            Output variables that receive user input data
        }

        input.close();
//        Close the Scanner object
    }
}
  • Create a Scanner object:
    • In the basic grammar we learned before, we did not realize the interaction between programs and people, but Java provides us with such a tool class that we can obtain user input. java.util.Scanner is a new feature of Java5, we can obtain user input through the Scanner class.
    • The input string is obtained through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is any input data.

Advanced Scanner

package CH02_JAVAProcessControl;
//Basic Scanner

import java.util.Scanner;

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

        System.out.println("Please enter 2");
        if (input.hasNextLine()) {

            String i2 = input.nextLine();
            System.out.println(i2);
        }
        input.close();
    }
}
  • The difference between hasNextLine and hasNext:
    • hasNextLine will record all data entered by the user until the Enter key is pressed
    • hasNext automatically stops when it encounters a space

Case Scanner

package CH02_JAVAProcessControl;
//Basic Scanner

import java.util.Scanner;

public class XZ01_UserInteraction3 {
    public static void main(String[] args) {
//        We can input multiple numbers, and calculate their sum and average, press Enter to confirm each input number, end the input by inputting a non-number and output the execution result:

        Scanner input = new Scanner(System.in);
        double sum = 0;
//        Declare variables to record user input data and
        int count = 0;
//        Declare variables to record the number of times the user enters data

        System.out.println("Please key in numbers(Enter the letter to stop)");
        while (input.hasNextDouble()) {
//          Only when the user enters Double type data will it be executed
            sum += input.nextDouble();
//            Records and variables, plus the user's current input data
            count++;
//            The number of times the user enters data +1
        }
        System.out.println(count + "The sum of the numbers is:" + sum);
        input.close();
    }
}
  • Sequential structure:
    • The basic structure of JAVA is a sequential structure, unless otherwise specified, it will be executed sentence by sentence in order.
    • The sequential structure is the simplest algorithmic structure.
    • Between the statement and the statement, between the box and the box is carried out in order from top to bottom, it is composed of several processing steps executed in sequence, and it is a basic algorithm structure that cannot be separated from any algorithm .

select structure

Single if selection structure

package CH02_JAVAProcessControl;

//single if
public class XZ02_SelectStructure {
    public static void main(String[] args) {
        int i = 60;

        if (i >= 60) {
            System.out.println("pass");
            //when the result is true
        } else {
            System.out.println("failed");
            //when the result is false
        }

    }
}
  • We often need to judge whether something is feasible before we execute it. Such a process is represented by an if statement in the program

Multiple if selection structure

package CH02_JAVAProcessControl;
//multiple if

import java.util.Scanner;

public class XZ02_SelectStructure2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
//      Determine the user input data and partition the data
        System.out.println("Please enter grade");
        double score = input.nextDouble();

        if (score > 100) {
            System.out.println("illegal data");
        } else if (score <= 100 && score >= 90) {
            System.out.println("A class");
        } else if (score >= 80) {
            System.out.println("B class");
        } else if (score >= 70) {
            System.out.println("C class");
        } else if (score >= 60) {
            System.out.println("D class");
        } else {
            System.out.println("failed");
        }

        input.close();
    }
}

Nested if selection structure

package CH02_JAVAProcessControl;
//nested if

import java.util.Scanner;

public class XZ02_SelectStructure3 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
//      Determine the user input data and partition the data
        System.out.println("Please enter grade");

        if (input.hasNextDouble()) {
            double score = input.nextDouble();
            //if determines whether the user input data is of type double
            if (score > 100) {
                System.out.println("illegal data");
            } else if (score <= 100 && score >= 90) {
                System.out.println("A class");
            } else if (score >= 80) {
                System.out.println("B class");
            } else if (score >= 70) {
                System.out.println("C class");
            } else if (score >= 60) {
                System.out.println("D class");
            } else {
                System.out.println("failed");
            }
        }

        input.close();
    }
}
  • The execution condition of the if statement:
    • If the execution result of the first if statement is true, all the following if statements will not be executed
    • That is, if if can enter the next judgment, it must not meet the condition of the previous if

switch selection structure

package CH02_JAVAProcessControl;
//switch judge integer

import java.util.Scanner;

public class XZ02_SelectStructure4 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please key in numbers");
        int var = input.nextInt();

        switch (var) {
            case 0:
                System.out.println("value 1");
                break;
            case 1:
                System.out.println("value 2");
                break;
            case 2:
                System.out.println("value 3");
                break;
            default:
                System.out.println("Defaults");

        }


        input.close();

    }
}
  • Select structure:

    • Another way to implement the multi-choice structure is the switch case statement.

    • A switch case statement tests whether a variable is equal to one of a series of values, each value is called a case.

  • Variable types in switch statements can be:

    • byte, short, int, or char
    • Starting from Java SE 7, switch supports string String type
    • At the same time, case labels must be string constants or literals.

Advanced switch selection structure

package CH02_JAVAProcessControl;
//switch judgment string

import java.util.Scanner;

public class XZ02_SelectStructure5 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("please input the value");
        String var = input.next();

        switch (var) {
            case "Xuanzi":
                System.out.println("Xuanzi");
                break;
            case "XuanZiShaer":
                System.out.println("XuanZiShaer");
                break;
            default:
                System.out.println("Defaults");

        }

        input.close();

    }
}

Select Structure Case

package CH02_JAVAProcessControl;
//     Enter a date to determine how many days have passed since this date

import java.util.Scanner;

public class XZ02_SelectStructure6 {
    public static void main(String[] args) {

//        Ordinary leap year: the Gregorian calendar year is a multiple of 4, and not a multiple of 100, it is a leap year.
//        Divisible by 4 and not divisible by 100
//        Century leap year: Years in the Gregorian calendar are in hundreds and must be a multiple of 400 to be a leap year).
//        Divisible by 100 and divisible by 400


        Scanner input = new Scanner(System.in);
        System.out.println("Please enter date year:");
        int year = input.nextInt();
        System.out.println("Please enter date month:");
        int month = input.nextInt();
        System.out.println("Please enter a date:");
        int day = input.nextInt();


        switch (month - 1) {
            case 11:
                day += 30;
            case 10:
                day += 31;
            case 9:
                day += 30;
            case 8:
                day += 31;
            case 7:
                day += 31;
            case 6:
                day += 30;
            case 5:
                day += 31;
            case 4:
                day += 30;
            case 3:
                day += 31;
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    System.out.println("leap year");
                    day += 29;
                } else {
                    System.out.println("average year");
                    day += 28;
                }
            case 1:
                day += 31;
                break;
        }
        System.out.println(day);
        input.close();
    }
}

loop statement

while loop statement

package CH02_JAVAProcessControl;

//while output the sum within 100
public class XZ03_CirculateStructure {
    public static void main(String[] args) {
        int sum = 0;
        int i = 0;
        while (i <= 100) {

            sum += i;
            i++;
        }
        System.out.println(sum);
    }
}
  • while is the most basic loop, its structure is:
    • The loop executes as long as the Boolean expression is true.
    • In most cases, we will stop the loop, and we need a way to invalidate the expression to end the loop.
    • In a small number of cases, loops need to be executed all the time, such as server request response monitoring.
    • If the loop condition is always true, it will cause an infinite loop [infinite loop], and we should try to avoid infinite loops in our normal business programming. It will affect the performance of the program or cause the program to freeze and crash!

do...while loop statement

package CH02_JAVAProcessControl;

//The difference between do while and while
public class XZ03_CirculateStructure2 {
    public static void main(String[] args) {
        int i = 0;

        while (i < 0) {
            i++;
            System.out.println(i);
        }
        System.out.println("=====================");
        do {
            i++;
            System.out.println(i);
        } while (i < 0);
    }
}
  • do...while loop:

    • For the while statement, if the condition is not met, the loop cannot be entered. But sometimes we need to execute at least once even if the condition is not met.
    • The do...while loop is similar to the while loop, except that the do...while loop executes at least once.
  • The difference between while and do...while:

    • while judges first and then executes. dowhile is executed first and then judged!
    • Do...while always guarantees that the loop body will be executed at least once!
    • This is their main difference.

for loop statement

package CH02_JAVAProcessControl;

//The for loop outputs the sum within 100
public class XZ03_CirculateStructure3 {
    public static void main(String[] args) {

        int a = 0;
              //Initialization //Condition judgment //Iteration
        for (int i = 0; i <= 100; i++) {

            a += i;
        }
        System.out.println(a);

    }
}
  • for loop:

    • Although all looping structures can be represented by while or do...while, Java provides another statement - the for loop, which makes some looping structures easier.
    • The for loop statement is a general structure that supports iteration, and it is the most effective and flexible loop structure.
    • The number of times the for loop executes is determined before execution.
  • for loop execution steps:

    1. Initialization steps are performed first. Can declare a type but initialize one or more loop control variables, or an empty statement.
    2. Then, check the value of the Boolean expression. If true, the loop body is executed. If false, the loop terminates and the statement following the loop body starts executing.
    3. After executing a loop, update the loop control variable (the iteration factor controls the increase or decrease of the loop variable).
    4. Check boolean expressions again. Loop through the above process.

Enhanced for statement

package CH02_JAVAProcessControl;

//enhanced for
public class XZ03_CirculateStructure7 {
    public static void main(String[] args) {
//iterate through the values ​​in the array
        int[] a = new int[]{10, 20, 30, 40, 50, 60};
        for (int x :
                a) {
            System.out.println(x);
        }
    }
}
  • Enhanced for:
    • Java5 introduced an enhanced for loop mainly for use with arrays or collections.
    • Declaration Statement: Declare a new local variable whose type must match the type of the array element. Its scope is limited to the loop statement block, and its value is equal to the value of the array element at this time.
    • Expression: The expression is the name of the array to be accessed, or a method that returns an array.

The difference between break and continue

package CH02_JAVAProcessControl;

//The difference between break and continue
public class XZ03_CirculateStructure1_break_continue {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            i++;
            System.out.print(i + "  ");
            if (i == 30) {
                break;
            }
        }
System.out.println();
 System.out.println("==============================");
        int j = 0;
        while (j < 100) {
            j++;
            if (j % 10 == 0) {
                System.out.println();
                continue;
            }
            System.out.print(j);
        }


    }
}
  • The difference between break and continue:
    • break In the main part of any loop statement, break can be used to control the flow of the loop. break is used to forcibly exit the loop without executing the remaining statements in the loop. (The break statement is also used in the switch statement)
    • The continue statement is used in the loop statement body to terminate a certain loop process, that is, to skip the unexecuted statements in the loop body, and then to determine whether to execute the loop next time.

goto keyword

package CH02_JAVAProcessControl;

public class XZ04_GoToKeyWord {
    public static void main(String[] args) {
//      Print all prime numbers between 101-159 ~
//      A prime number is a natural number that has no other factors than 1 and itself among the natural numbers greater than 1.

        int count = 0;
        //Not recommended for use!
        outer:
        for (int i = 101; i < 150; i++) {
            for (int j = 2; j < i / 2; j++) {
                if (i % j == 0) {
                    continue outer;
                }
            }
            System.out.print(i + " ");
        }

    }
}
  • goto keyword:
    • About the goto keyword The goto keyword has been around for a long time in programming languages.
    • Although goto is still a reserved word in Java, it is not officially used in the language; Java does not have goto.
    • However, in the two keywords break and continue, we can still see some shadows of goto - labeled break and continue.
    • "Label" means an identifier followed by a colon, eg: label:
    • The only place where labels are used in Java is before a loop statement. The only reason to set a label before a loop is if we want to nest another loop within it, since the break and continue keywords usually only break the current loop, but if used with a label, they will break where the label exists.

Cyclic structure case - sum of odd and even numbers within 100

package CH02_JAVAProcessControl;

//The for loop outputs the sum of odd and even numbers within 100
public class XZ03_CirculateStructure4 {
    public static void main(String[] args) {

        int ji = 0;
        int oh = 0;
        for (int i = 0; i <= 100; i++) {
            if (i % 2 == 0) {
                oh += i;
            } else {
                ji += i;
            }
        }
        System.out.println(ji);
        System.out.println(oh);
        System.out.println(ji + oh);

    }
}

Loop structure case-numbers divisible by 5 between 1-1000, and output 3 per line

package CH02_JAVAProcessControl;

//Use while or for loop to output numbers divisible by 5 between 1-1000, and output 3 numbers per line
public class XZ03_CirculateStructure5 {
    public static void main(String[] args) {


        for (int i = 1; i < 1000; i++) {
            if (i % 5 == 0) {
                System.out.print(i + "\t");

            }
            if (i % (3 * 5) == 0) {
                System.out.println();
            }
        }
    }
}

Loop structure case - printing positive and negative 99 multiplication table

package CH02_JAVAProcessControl;

//Print positive and negative 99 multiplication table
public class XZ03_CirculateStructure6 {
    public static void main(String[] args) {

//      1. Let's print the first column first, everyone should know this
//      2. We wrap the fixed 1 with a loop
//      3. Remove duplicates, i<=j
//      4. Adjust the style

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

        }
        System.out.println("===========================");

        for (int j = 9; j >= 0; j--) {
            for (int i = 1; i <= j; i++) {
                System.out.print(j + "*" + i + "=" + (j * i) + "\t");
            }
            System.out.println();

        }

    }
}

Cyclic Structure Example - Printing Triangles

package CH02_JAVAProcessControl;

//print triangle
public class XZ03_CirculateStructure8 {
    public static void main(String[] args) {
// Relationship between blank and entity 2*i-1
        for (int i = 0; i <= 5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= 2 * i - 1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        System.out.println("===========================");

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

Xuanzi November 27, 2022

Tags: Java jvm Interview

Posted by marsooka on Mon, 28 Nov 2022 07:52:35 +0300