javase_code's first big job --- concatenation of knowledge points: Scanner, Random, while loop, if judgment, equals of String class and for loop

1. Senior 01 の learning suggestions: ↓

  • Java is a system. Not only learn Java, but also database.

  • The prophet knows why again.
  • If you don't understand a point, put it first and look at the key points later.
  • After each stage of study, you should do a big homework.
  • We should string together knowledge. (PS: next, want to make Gobang!!)

    For example, after learning the array, make a Gobang. → there is no interface. It is on the console. Just print it out.

    Replace the chessboard with special characters. sop output, combined, is a chessboard. Just print it

    No matter what design patterns, object-oriented and encapsulated concepts.

  • We should string up the knowledge points. Knowledge points are in bulk and should be connected through large operations.

-------------------Thank you for your help----------------------

2. Received the javase from Xiaobai aka chaxian °_ Code big homework first experience! AOA

2.1Step01: realize the output display of the menu

  • ★★★ knowledge points used in Step01:

  • 1. Output menu through Scanner

  • 2. Output statements, print "menu", "1. Registration", "2. Login", "3. Lottery", "4. Exit"

Search → java menu (menu bar, menu and menu items) Huixin's eye blog - CSDN blog java menu

I saw other knowledge points in that article. I didn't learn them. I thought I could continue. Ha ha, naive

 break 0813 10:37

------------------------------------------------

Xiaobai 14:43:25

JMune, don't use it

Xiaobai 14:43:35

You use system out. println

Xiaobai 14:43:56

You use JMenu to involve Java GUI

Xiaobai 14:44:24

I use Java GUI in the teaching of confession program

Through xiaobaijun's explanation, I found that I complicated the problem emmm.

  • ★★★ Step01 precautions: write what the function needs. You can't write more. Understanding the requirements is the first! Don't complicate the problem!

 

  • step01 complete code display ↓.

import javax.swing.*;
import java.util.Random;
import java.util.Scanner;

/*
task
1,Simulate the whole process of registration and login lucky draw
2,major function 
3,Sign up for the lucky draw

Phase 1: Exercise - realize the output display of the menu
 Requirement description
1,Output menu
2,Select menu number and output menu information
3,If the number selection is wrong, output "your input is wrong!"

Idea:
1,If you want to output, you need to use Scanner
2,How to choose? → search and see → java menu (menu bar, menu and menu items) Huixin's eye blog - CSDN blog _javamenu
        (★★@Tea fairy: output directly without JMenu)
    2.1 How to enter the menu through Scanner? → use array list?
    2.2 So, is this to use Random to generate Random numbers?
    2.3 What is required after generating random numbers in the range of 0 ~ 100---
        2.3.1 Select menu number and output menu information. This sentence aka can only choose one number?
        2.3.2
3,If you need to output a statement, how do you indicate a selection error--- Do you want to judge?
★★★break 20210813 15:28 @Tea Fairy - this stage only needs to practice output.
 */
public class Step01 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
/*
         * @author Jerrycjazz
         * @create 2021-08-13-10:37

        //add(JMenu m);
        System.out.println("Please enter the menu: "); / / output directly without JMenu

        int ArrayList = sc.nextInt();//Use array list? Should I fill in the numbers in the brackets?
                                    // Not filled → 23 53 13 34 46 70 aka can output array

        Random r = new Random(); //2.2 Do you want to use Random to generate Random numbers? So do you fill in the brackets? → it should be filled in. The parameter represents the range
        int num = r.nextInt(101); //So what about those who want to fill in the range of 0 ~ 100? → note: close the left and open the right section.
*/

        /**
         * @author Tea fairy °
         * @create 2021-08-13-14:51
         */
        System.out.println(" menu");
        System.out.println("");
        System.out.println(" 1.register");
        System.out.println( " 2.Sign in");
        System.out.println(" 3.luck draw");
        System.out.println(" 4.sign out");
        System.out.println(" ");
        System.out.print(" >");
    }
}

2.2Step02: realize circular execution function.

  • ★★★ knowledge points used in Step02:

  • 1. Scanner for keyboard input
  • 2. Output a statement asking the user "continue?"
  • 3. While loop: (define a name {w when writing a while loop)
    • 3.1 need if judgment: judge whether to continue. If yes, select the menu. If no, end the cycle. If the input is wrong, you will be prompted that the input is wrong. if("yes".equals(a)){//PS: got new knowledge -- equals: it is used for judgment and for String class.
    • 3.2 else if, the user selects no to end the cycle (break w;)
    • 3.3 else output ("input error, please re-enter (yes / no)");
  • ★★★ Step02 precautions (if conditions are not written correctly):

  • Variables cannot be defined or assigned in if.
  • Judgment can only be performed in if.
  • For example, if is written as if(a = = 1).

2.1 if the user chooses to continue, how can this sentence be expressed by if? You should use while → Detailed explanation of keyboard input using Scanner class in Java

break 0813 16:10

back 0813  18:48

You need to judge. What if the user doesn't enter "continue". from little Bai Jun.

 

break 0813 19:31

Group friends say (change the Boolean in the previous step) to = = true.

After the group friend reminded: a is int and can't be assigned to Boolean. I didn't notice the change of QAQ!

Note: = = is comparison and = = is assignment! When reporting an error, first look at the number of wrong lines, find the corresponding error, and improve the error adjustment ability!

aka didn't connect the previous knowledge points. dbq Mr. Bi Xiangdong & Mr. Gao Qi!

 break 19:45

break 19:59

  • Variables cannot be defined or assigned in if.
  • Judgment can only be performed in if.
  • For example, if is written as if(a = = 1).

break 20210813-22:19

Step02 complete code (comment out your own mistakes and add tea fairy's) ↓:

import com.sun.deploy.security.SelectableSecurityManager;

import java.util.Scanner;

/*
Phase 2: Exercise - implementing circular execution
 Requirement description
1,The system asks the user whether to continue.
2,If the user chooses to continue, you can continue to select the menu, otherwise the program ends and exit the system.

Idea:
1,Scanner is required for keyboard input
2,Need to judge if
    2.0 How to achieve this --- input "continue" on the keyboard and directly use output?
    2.1 If the user chooses to continue, how can this sentence be expressed by if? You should use while → https://www.cnblogs.com/liuzengzhi/p/11765704.html
        2.1.1 Or should we use if to judge, aka if the user does not enter "continue".
     ↑(Back to the origin) 2.1 2. If the user chooses to continue, how can this sentence be expressed by if?
        2.1.3 Variable required.
        2.1.4 So how do you write conditions in if brackets?
 */

public class Step02 {
/*
        * @author Jerrycjazz
        * @create 2021-08-13-19:49
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(" Would you like to continue? ");

        int a = sc.nextInt();//2.1.3 Variable required.
        //while(sc.hasNextLine()){//2.1 If the user chooses to continue, what does this mean? You should use while
          //  System.out.println("Please continue to select the menu: "+ sc.nextLine());}
        boolean userPrint;
        if(userPrint = true){
            System.out.println("Please select the menu: "); / / the compilation has passed, but" please select the menu "is not displayed on the screen
        }else//else Write after these braces!
            return;
    }
*/
    /**
     * @author Tea fairy °
     * @create 2021-08-13-22:01
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(" Would you like to continue( yes / no)?");//Added a prompt for user input

        w:while(true){// Cycle Name: w

            String a = sc.next();//
            //Judge whether to continue. If yes, select the menu. If no, end the cycle. If the input is wrong, you will be prompted that the input is wrong
            if("yes".equals(a)){//PS: got new knowledge -- equals: it is used for judgment and for String class
                System.out.println("Please select the menu, please enter( yes / no): ");
            }else if("no".equals(a)){
                break w;// End the loop named: w (PS: Yes, yes, it's better to add w after break)
            }else{
                System.out.println("Input error, please re-enter( yes / no)");
            }
        }
    }
}

2.3Step03: realize the registration function.

  • ★★★ knowledge points used in Step03:

  • 1. Scanner and Random are required.
  • 2. How to write Random that generates 4-bit Random numbers? for loop.
  • 3. Create user data store
  • 4. Store the user login information
  • ★★ Step03 precautions:

  • 1,2.1. 1. Connect the generated random numbers. How to write?
    • aka generates four random integers between 0 and 9, adds them to the set, and traverses the set.
    • from tea fairy °: when someone registers, there must be a place to store his registration information. We only consider one person. Then we can use variables instead of arrays and collections to store his information.
  • 2. 2.2 how to express the registration mark? from tea fairy °: not for the time being.

The input string of tea fairy cannot be modified:

Xiaobai: 21:30:02 on August 14, 2021
Change your card number to String?
Why?

S**y 2021/8/14 21:30:31
So I made a mistake?
dbq (↓ changed)

Step03 write your own code (not all correct after modification) ↓:

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

/*
Phase 3: Exercise - Implementing the registration function
o Requirement description
1,Enter the user name and password, and the system generates a 4-digit random number as the card number.
2,If the registration is successful, display the registration information and modify the registration ID to true.

Idea:
1,Scanner and Random are required.
    1.1 How to write Random that generates 4-bit Random numbers? for loop.

2,Using Scanner again,
    2.1 How to write the registration information? Use the output statement.
        2.1.1 Let the generated random numbers be connected, how to write?
            aka Generate 4 random integers between 0 and 9, add them to the set, and traverse the set.
            Idea:
            1,You need to store 4 numbers and create a set, < integer >
            2,Random is required to generate random numbers
            3,Loop 4 times to generate 4 random numbers, for loop.
            4,Call r.nextInt(int n) within the loop, and the parameters are 9,0 ~ 10
            5,Add the number to the set, add.
            6,Traversal collection: for, size, get.
        2.1.2 When the registration is successful and the registration information is displayed, how to indicate the generated 4 random number passwords in parentheses?
            //System.out.println("User name: "+ str +" password: "+ passworldvip";

         from Tea fairy: when someone registers, there must be a place to store his registration information. We only consider one person,
            So we can use variables instead of arrays and collections to store his information.
    2.2 How to represent the registration ID? from tea fairy °: not for the time being.
    2.3 System.out.println("Your card number is: "+ sc); / / the card number is not written correctly, but the address value is output.
 */
public class Step03My {
    /**
     * @author Jerrycjazz
     * @create 2021-08-14-15:32
     */
    public static void main(String[] args) {
        System.out.println("Please enter your user name and password:");
        Scanner sc = new Scanner(System.in);

        //System.out.println("please enter your password:");
        String str = sc.next();//ps: not familiar with Scanner string input
        String str2 = sc.next();//Both username and password should be set to string type. Do not int num = sc.nextInt();

        /*
        Random r = new Random();
        for (int i = 0; i < 4; i++) {
            int num2 = r.nextInt(10);//The left closed right open interval is 0 ~ 9
            //System.out.print("Your card number is: "+ num2); / / your card number is: 7 your card number is: 7 your card number is: 1 your card number is: 3

        ArrayList<Integer> list = new ArrayList<>();
        Random r = new Random();

        for (int i = 0; i < 4; i++) {
            int num = r.nextInt(10);
            list.add(num);
        }
        //Traverse the collection.
        for (int i = 0; i < list.size(); i++) {
            System.out.print("Your card number is: "+ list.get(i));//2.1.1 connect the generated random numbers. How to write?
        }
*/
        Random r = new Random();

        System.out.println("Your card number is:"+sc);//The card number is not written correctly. The output is the address value.

        int passWorldVip = r.nextInt(9999 - 1000 + 1)+1000;//Name the resulting random array.

        System.out.println();
        System.out.println("Registration succeeded. Your registration information is:");
        System.out.println("user name:"+str +"Password is:"+ passWorldVip);// 2.1. 2 how to represent the generated four random number passwords in parentheses?
        //System.out.println("user name:" + str + "password:" + R ")// java. util. Random@12a3a380
    }
}

Step03 code written by tea Fairy (after modification, the string AOA can be entered) ↓:

import java.util.Random;
import java.util.Scanner;

public class Step03ChaXian {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random r = new Random();
        /**
         * @author Tea fairy °
         * @create 2021-08-14-16:01
         */

        //Create user data store
        String name;
        String passWorld;
        int passWorldVip;

        System.out.println("Please enter your user name and password:");

        //Store the user login information
        String textName = sc.next();
        name = textName;

        String textPassWorld = sc.next();
        //int textPassWorld = sc.nextInt();
        passWorld = textPassWorld;

        //String textPassWorldVip = sc.next(9999 - 1000 + 1) + 1000;
        int textPassWorldVip = r.nextInt(9999 - 1000 + 1) + 1000;//Name the resulting random array.
        passWorldVip = textPassWorldVip;

        System.out.println("Your card number is:" + passWorldVip);

        //Enter the information registered by the user
        System.out.println();
        System.out.println("Registration succeeded. Your registration information is:");
        System.out.println();
        System.out.println("user name:" + name + ", Password is:" + passWorld + ", Membership card No.:" + passWorldVip);
    }
}

2.4Step04: realize login function

  • ★★★ knowledge points used in Step04:

  • 1. Scanner and output statements are required.
  • 2. Indicates an input error. You need to output a statement to prompt the user to continue input, and then use if to judge.

  • ★★★ Step04 precautions:

  • 1. In addition to the if judgment, the variables that store the user name and password at the time of registration and the user name and password entered again should be put into the for loop.
  • 2. from xiaobaijun: let me tell you first: if you want to compare strings in the future, use equals.

    Format: variable name 1 Requests (variable name 2)

    Or "what you want to compare" Equals (variable name 1)

    Or "what you want to compare" equals("what you want to compare")

In this step, the runtime specially inputs different data to think it has been done, but it is found that there is no success in login in step 1, and the system prompts welcome information.

Add a sentence "sout h" and then ↓.

For ↑, if the same data is intentionally entered, the input error is still prompted, and the program does not stop running.

from Xiaobai Jun:

Let me tell you first: if you want to compare strings in the future, use equals

Format: variable name 1 Requests (variable name 2)

Or "what you want to compare" Equals (variable name 1)

Or "what you want to compare" equals("what you want to compare")

According to the above knowledge, the small problem mentioned just now was finally solved, but it was finally found that the whole was broken, and the for loop was not written correctly.

Works of tea fairy ↓

In addition to the if judgment, the variables that store the user name and password at the time of registration and the user name and password entered again should be put into the for loop.

Step04 write your own code (wrong in the for loop) ↓:

import java.util.Scanner;
/**
 * @author Jerrycjazz
 * @create 2021-08-14-21:51
 */
/*
Phase 4: Exercise - Implementing the login function
 Requirements Description:
1,Enter the user name and password at the time of registration. After successful login, the system will prompt welcome information.
2,If the user name and password are entered incorrectly, the user will be prompted to continue to enter, and there will be at most 3 input opportunities.

Idea:
1,Scanner and output statements are required.
2,How does this indicate an input error? Do you use Scanner to let the user input again on the keyboard? If the two times are different, do you enter the wrong meaning?
    2.1 You need to output a statement to prompt the user to continue input, and then use if to judge
 */
public class Step04My {

    public static void main(String[] args) {
        System.out.println("Please enter your registered user name and password:");
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        String str2 = sc.next();

        System.out.println("Please enter your user name and password again:");
        Scanner sc2 = new Scanner(System.in);
        String str3 = sc.next();
        String str4 = sc.next();

        for (int i = 0; i < 3; i++) {
            //if (sc2 != sc){
            if (!str1.equals(str2) && !str2.equals(str4)){
                System.out.println("The user name and password are entered incorrectly. Please re-enter the user name and password:");
                Scanner sc3 = new Scanner(System.in);
                String str5 = sc.next();
                String str6 = sc.next();
            } else {
                System.out.println("Login succeeded, welcome!");//Three "login succeeded, welcome!" are printed out,
                        // So the for loop is not written correctly. qaq is written correctly by the tea Fairy / / return;
            }
        }
    }
}

Step04 code written by tea fairy ↓:

import java.util.Scanner;
/**
 * @author Tea fairy °
 * @create 2021-08-14-21:41
 */
public class Step04ChaXian {

    public static void main(String[] args) {
        System.out.println("Please enter your registered user name and password:");
        Scanner sc = new Scanner(System.in);

        for (int i = 0; i < 3; i++) {
            //user name
            String str1 = sc.next();
            //password
            String str2 = sc.next();

            System.out.println("Please enter your user name and password again:");
            //user name
            String str3 = sc.next();
            //password
            String str4 = sc.next();

            if (!str1.equals(str2) && !str2.equals(str4)) {
                System.out.println("The user name or password is entered incorrectly. Please re-enter the user name and password:");

            } else {
                System.out.println("Login succeeded, welcome!");
                return;
            }
        }
    }
}

2.5 step05: realize lucky draw function

 

Xiaobaijun: why do you want to do it separately? You said you knew it was the whole thing.

Me: Well, we should pay attention to it in the future, but it's difficult to get a single one. Will the whole one be all right

Xiaobaijun: you go and run the project I have done well

Me: I really can't adjust such a big one now. The code is close to 180 lines of QAQ

★★★ note: learn to analyze the train of thought of the whole exercise! Instead of doing it every step, it's easy to pay attention to details rather than focus on the whole. This is not an object-oriented idea.

★★★ review --- summary of the use of object-oriented in requirements:

1. First, extract the objects in the problem domain according to nouns.

2. To describe an object, you should specify the attributes and functions of the object.

3. You can create the specific object of the thing through new.

4. Call its subsequent functions through the object.

The focus of java is object-oriented, not process oriented. However, writing code later will also involve process oriented, aka because we need to implement a function and talk about some logical things. Talk about the specific implementation of some functions, which must also be a process.

  • ★★★ knowledge points used in Step05:

  • 1. Exception loop while(true).
  • 2. Call method important.
  • 3. Menu method aka menu output.
  • 4. Scanner and Random, user data storage.
  • 5. Judgment --- whether to register (if), log in (switch --- log in to judge if, else if lottery), and whether the Vip number is input correctly (3 input opportunities, for loop)
    • 6. for loop --- traverse the lucky number.
    • 7. for loop --- when the VIP card number is input correctly, compare the lucky number with the card number, and write if to judge whether it is a lucky member.
    • 8. else if --- exit.
    • 9. else --- input error, remind to re-enter (1 ~ 4).

It's much clearer to do it again. AOA:

1. When the while(true) menu is output: if judgment --- whether to register, else if judge whether to register when you choose to log in later.
2. switch --- log in to judge if and else if lucky draw.
3. If judgment - whether you have logged in and in the for loop - if judgment is made on whether the Vip card number is correct, and there are three input opportunities.
3.1 for loop --- traverse the lucky number.
3.2 for loop --- when the VIP card number is entered correctly, compare the lucky number with the card number, and write if to judge whether it is a lucky member.
3.3 else if --- exit.
3.4else --- if the input is wrong, remind to re-enter (1 ~ 4).

import java.util.Random;
import java.util.Scanner;

/**
 * @author Tea fairy °
 * @create 2021-08-14-23:19
 */
public class project {

    public static void main(String[] args) {

        //Abnormal cycle
           while (true){
               try {
                   //Call method important
                   important();
               }catch (Exception e){
                   System.out.println("Sorry, your input is wrong. You can only enter numbers in the menu");
               }
           }
    }


    //Menu method
    public static void show(){
        //Menu output
        System.out.println("       menu");
        System.out.println("");
        System.out.println("     1.register");
        System.out.println("     2.Sign in");
        System.out.println("     3.luck draw");
        System.out.println("     4.sign out");
        System.out.println(" ");
        System.out.print(" > ");
    }

    public static void important(){
        //Scanner and Random classes
        Scanner sc = new Scanner(System.in);
        Random r = new Random();

        //User data storage
        String name = null;
        int passworld = 0;
        int Vip = 0;

        //identification
        boolean isFlag = false;
        boolean isFlag2 = false;

    
        while(true){
            //Menu output
            show();
            int num = sc.nextInt();
            //1 representative registration
            i:if (num == 1){
                //If the identity is set to true, it means you can log in
                isFlag = true;

                //Register information and store it
                System.out.println(" ");
                System.out.print("full name > ");
                name = new Scanner(System.in).next();

                System.out.print("password > ");
                passworld = sc.nextInt();

                int numVip = r.nextInt(9999 - 1000 + 1)+1000;
                Vip = numVip;
                System.out.println("Your membership number > " + numVip);

                //Display the filled information
                System.out.println("        Data completed!!!");
                System.out.println("");
                System.out.println("full name > "+name);
                System.out.println("password > "+passworld);
                System.out.println("Your membership number > "+Vip);

            }else if (num == 2){//Sign in
                //Determine whether you are registered
                if (isFlag == false){
                    System.out.println("Please register before logging in. Thank you");
                    break i;
                }
                isFlag2 = true;

                //Login judgment
                switch (num){
                    case 2:

                        f:for (int i = 3; i >= 1; i--) {

                            System.out.print("full name > ");
                            String text = sc.next();

                            System.out.print("password > ");
                            int passWorldText = sc.nextInt();

                            System.out.print("Your membership number > ");
                            int VipText = sc.nextInt();

                            if (!text.equals(name) || passWorldText != passworld || VipText != Vip) {
                                System.out.println("Your name, password or membership number is incorrect. Please check it and fill it in again, You still have" + --i + "Second chance");
                            }else {
                                System.out.println("Login succeeded");
                                break i;
                            }
                        }
                        break;
                }


            }else if (num ==3){//luck draw

                //Determine whether you have logged in
                if (isFlag2 == false){
                    System.out.println("Please log in first and then draw the lottery. Thank you");
                    break i;
                }

                //Show welcome user name
                System.out.println("welcome "+name);
                System.out.println("");

                //Judge whether the Vip card number is correct, and there are 3 input opportunities
                f:for (int i = 3; i >= 1; i--) {
                    System.out.print("Please fill in your membership number > ");
                    Scanner sc3 = new Scanner(System.in);
                    int VipText2 = sc3.nextInt();
                    if (Vip == VipText2){
                        break f;
                    }else{
                        System.out.println("You have" + i + "Opportunity to fill in");
                    }
                }

                System.out.println("Your membership number > "+Vip);

                int[] arr = new int[5];

                //When the Vip card number is entered correctly, enter the comparison card number
                // If the random number appears exactly the same as your card number, it will output: Congratulations, you are today's lucky member
                //Otherwise output: sorry, you are not a member today
                System.out.print("Today's lucky members are:");
                for (int i = 0; i < 5; i++) {
                    int i1 = r.nextInt(9999 - 1000 + 1)+1000;
                    arr[i] = i1;
                    System.out.print(i1+" ");
                    System.out.println(" ");
                }

                for (int i = 0; i < arr.length; i++) {
                    if (Vip == arr[i]){
                        System.out.println("Congratulations, you are a lucky member today");
                        break i;
                    }
                }
                System.out.println("Sorry, you are not a member today");

                //sign out
            }else if(num == 4){
                System.exit(0);

                //Output if input is wrong: sorry, your input is wrong, please re-enter (1 ~ 4) >
            }else{
                System.out.println("Sorry, your input is wrong, please re-enter (1~4) > ");
            }

        }
    }
}

3. Postscript: don't write so long and so many pictures next time. Try to simplify them as much as possible

Finally, thank you to my little friend: Xiaobai aka tea fairy

The game written is also very fun!

Keywords: Java

Added by jimpat on Wed, 22 Dec 2021 22:12:06 +0200