Introduction to JAVA -- case exercise

1. Review of Episode I

When do methods constitute overloads:

  • Must be in the same class
  • Method names must be consistent
  • The parameters must be different (the number of parameters is different, the type of parameters is different, and the order of types is different)
  • It has nothing to do with the return value

The first condition, the second condition and the third condition must be met at the same time to calculate the overload of the method.

What are the benefits of method overloading?
  • For method definer:

    The method name of the same function will be defined as the same. You don't need so many different names.

  • For method callers:

    There is no need to remember so many method names. For methods with the same function, just remember one.

Parameter passing of method:

  • When a method is called, the basic data type is passed

    When a method is called, all that is passed are variable records, basic data types, and real values are recorded.

    Value passed.

  • When the method is called, the reference data type is passed

    When calling a method, it also passes the variable record, references the data type, and records the address value.

    The address value is passed.

Debug (you can use it)

Function:

You can see how the code runs step by step.

  • Break

    • If you want to see all the code

      The first line of valid statements of each method is preceded by a breakpoint. Just type one method.

    • If you want to see the local code

      Where won't you order

  • Run debug mode

    Right click the blank space and click debug

  • Look where

    Look at the debugger interface and the console interface below.

    debugger interface: the operation of the method.

    Method.

    Console interface: output statements

    If there is keyboard entry, it also needs to be entered on the console. Otherwise, debug cannot go to the next step.

  • Click next to run debug step by step.

    Click the shortcut key F7

    Or click step into with the mouse

  • Stop debug

    Click the Red Square on the left of the console. (operation indicator)

  • Cancel breakpoint

    Few breakpoints: click Cancel directly and manually.

    More breakpoints: click the button with multiple red squares overlapping on the left side of the console.

2. Sum

Title:

There is such an array. The elements are {68,27,95,88171996,51210}.

Find the sum of elements that meet the requirements in the array,

The requirement is: the sum element can't have 7 bits and 10 bits, and can only be an even number

Steps:

1. Define an array

2. Loop through the array to get each element

3. Judge whether each element meets the conditions

4. Accumulate the numbers that meet the conditions (at this time, you need to go back to the outside of the loop and define a summation variable)

5. Output results at the end of the cycle

answer:
public class Test1 {
    public static void main(String[] args) {
       /* There is such an array. The elements are {68,27,95,88171996,51210}.
        Find the sum of elements that meet the requirements in the array,
        The requirement is: the sum element can't have 7 bits and 10 bits, and can only be an even number*/


        //analysis
        //1. Define an array
        int[] arr = {68, 27, 95, 88, 171, 996, 51, 210};
        int sum = 0;
        //2. Loop through the array to get each element
        for (int i = 0; i < arr.length; i++) {
            //i --- represents each index in the array in turn
            //arr[i] - represents each element in the array in turn
            //3. Judge whether each element meets the conditions
            if ((arr[i] % 10 != 7) && (arr[i] / 10 % 10 != 7) && (arr[i] % 2 == 0)) {
                //4.  If the conditions are met, the sum is accumulated, otherwise it doesn't matter.
                sum = sum + arr[i];//sum += arr[i];   ---  sum = (int)(sum + arr[i])
                System.out.println(arr[i]);
            }
        }
        System.out.println("Sum is" + sum);

    }
}

3. Statistics

Title:

There is such an array. The elements are {68,27,95,88171996,51210}.

How many statistics meet the conditions?

The requirement is: the sum element can't have 7 bits and 10 bits, and can only be an even number

Steps:

1. Define an array

2. Loop through the array to get each element

3. Judge whether each element meets the conditions

4. Accumulate the numbers that meet the conditions (at this time, you need to go back to the outside of the loop and define a summation variable)

5. Output results at the end of the cycle

answer:
public class Test2 {
    public static void main(String[] args) {
        /* There is such an array. The elements are {68,27,95,88171996,51210}.
        How many statistics meet the conditions?
        The requirement is: the sum element can't have 7 bits and 10 bits, and can only be an even number*/

        //skill:
        //Once you see in the title, you have to count. (how many are there)
        //Then you must use the counter idea.
        //Define a variable with an initialization value of 0
        //When the conditions are met, the variable can be automatically increased once.


        //analysis
        //1. Define an array
        int[] arr = {68, 27, 95, 88, 171, 996, 51, 210};
        //Defining a counter is actually a variable
        int count = 0;
        //2. Loop through the array to get each element
        for (int i = 0; i < arr.length; i++) {
            //i --- represents each index in the array in turn
            //arr[i] - represents each element in the array in turn
            //3. Judge whether each element meets the conditions
            if ((arr[i] % 10 != 7) && (arr[i] / 10 % 10 != 7) && (arr[i] % 2 == 0)) {
                //4.  If the conditions are met, the counter will increase automatically.
                count++;
            }
        }
        System.out.println("The eligible numbers are" + count + "individual");
    }
}

4. Find elements

Title:

An array arr = {19, 28, 37, 46, 50} is known; Enter a data on the keyboard to find the index of the data in the array.

And output the index value found in the console. If not found, output - 1

Steps:

1. Define an array

2. Enter a number on the keyboard to compare with the number in the array

3. Define a counter to record how many times the current number appears in the array

4. Loop through the array to get each element in turn.

5. Compare the number entered by the keyboard with the elements in the array.

6. If the conditions are met, the current index will be printed. Counter++

7. Judge the counter. If it is 0, it means that the number has not existed in the array. Print - 1

answer:
public class Test3 {
    public static void main(String[] args) {
        //Shortcut keys for comment codes
        //1. Select the code to comment
        //2. Press the shortcut key ctrl + / single line comment
        //            ctrl + shift + / multiline comment


/*        An array arr = {19, 28, 37, 46, 50} is known; Enter a data on the keyboard to find the index of the data in the array.
        And output the index value found in the console. If not found, output - 1*/

        //analysis:
        //1. Define an array arr = {19, 28, 37, 46, 50};
        int [] arr = {19, 28, 37, 46, 50};

        //2. Enter a number on the keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a number");
        int number = sc.nextInt();//The accepted variable on the left of the quick generation method is ctrl + alt + v
        //3. Find the entered number and the index in the arr. If it does not exist, - 1
        //Q: under what circumstances can we think that the number entered by the keyboard does not exist in the array?
        //Flexible operation counter idea. Count how many times number appears in the array?
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            //Judge whether the number entered by the keyboard is equal to the currently traversed array.
            if(arr[i] == number){
                //If equal, the index is printed
                System.out.println(i);
                //Indicates that the number entered by the keyboard appears once.
                count++;
            }
        }
        //When the loop ends, the value of count indicates that the number entered by the keyboard appears several times in the array.
        //Because only after the loop is completed can all the elements in the array be found, and then - 1 can be printed
        if(count == 0){
            //If count is 0, the number entered on the keyboard does not exist.
            System.out.println(-1);
        }
    }
}

5. The numbers that meet the conditions are stored in the array

Title:

Store the number that can be divided by 5 between 10 – 20 into the array. The storage position is required to be random. Finally, traverse the array.

Steps:

1. First determine the number of qualified figures?

2. Use the number to create an array.

3. Traverse the qualified numbers in this range again and store them in the array.

4. Random position after storage.

5. Finally traverse.

answer:
public class Test4 {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 10; i <= 20; i++) {
            if (i % 5 == 0) {
                count++;
            }
        }
        //After the loop ends, the value of count is actually the length of the array
        System.out.println(count);
        //2. Create an array
        //Define a variable to represent the index of the current number to be stored
        int index = 0;
        int [] arr = new int[count];
        //3. Qualified numbers can be stored in the array.
        for (int i = 10; i <= 20; i++) {
            if (i % 5 == 0) {
                //Into the array.
                //Format:
                arr[index] = i;
                index++;
            }
        }
        //3. Traversal array
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

Again, disrupt the order of numbers in the array.

public class Test5 {
    public static void main(String[] args) {
        //Disorder the order of numbers in an array
        //After the last question, the numbers in the array are like this.
        int[] arr = {10, 15, 20};

        Random r = new Random();
        //Traversal array
        for (int i = 0; i < arr.length; i++) {
            //Gets a random index. (0 1 2)
            int randomIndex = r.nextInt(arr.length);
            //Exchange the i index with the numbers on the random index
            int temp  = arr[i];
            arr[i] = arr[randomIndex];
            arr[randomIndex] = temp;
        }

        //Traversal array
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

6. Get random characters

Title:

Create a character array and store A-Z and A-Z in the array. And get a random character from the array

Steps:

1. Define an array with a length of 52. Used to store A-Z, A-Z

2. Store A-Z into the array

3. Store a-z into the array

4. Randomly obtain an element from the array

answer:
public class Test6 {
    public static void main(String[] args) {
//        Create a character array and store A-Z and A-Z in the array.
//        And get a random character from the array

        //Because the array needs to be stored in A-Z. a-z.  Therefore, the length of the array is 52
        char [] charArr = new char[52];
        //Store A-Z A-Z into the array.
        //ASCII code table

        int index = 0;
        for (int i = 'a' ; i <= 'z'; i++) {
            //What does i mean? Each character between character a and character z is represented in turn, and the corresponding number in the ASCII code table
            charArr[index] =(char)i;
            index++;
        }
        //When the loop ends, it means that lowercase a ~ lowercase z have been stored in the array

        for (int i = 'A' ; i <= 'Z'; i++) {
            //What does i mean? Represents each character from character A to character Z in sequence, and the corresponding number in the ASCII code table
            charArr[index] =(char)i;
            index++;
        }
        //When the loop ends, it means that uppercase A-Z and lowercase A-Z have been stored in the array.

       //Gets a random character in the array
        //Because of the contents of the array, I can't be sure.
        //So if you want to randomly get the elements in the array.
        //1. Obtain the random index.
        //2. Retrieve elements through index.
        Random r = new Random();
        //Get a random index
        int randomIndex = r.nextInt(charArr.length);
        //Get elements by index
        char c = charArr[randomIndex];
        //Output the resulting element
        System.out.println(c);

    }
}

7. Verification code

Title:

Generate a 5-digit verification code

The verification code consists of 4 (A-Z, A-Z) and 1 (0-9) characters

The number can be fixed in the last digit - for example, gAgZ6

Steps:

1. Create an array with a length of 52.

Because there are 52 uppercase characters + lowercase characters, the length of the array is 52

2. Store the uppercase A character to the uppercase Z character into the array.

3. Store the lowercase a character to the lowercase z character into the array.

4. Get a random element from the array.

  • Get a random index first
  • Get elements according to random index

5. Repeat step 4 for 4 times.

6. Get a number between 0 and 9.

answer:
public class Test8 {
    public static void main(String[] args) {
        //Generate a 5-digit verification code
        //The verification code consists of 4 (A-Z, A-Z) and 1 (0-9) characters
        //The number can be fixed in the last digit - for example, gAgZ6

        //1. Add A-Z A-Z to a character array.
        char [] charArray = new char[52];

        //Index indicates the index to be operated on
        int index = 0;
        for (int i = 'A'; i <= 'Z'; i++) {
            //i represents the number corresponding to the characters between 'A' and 'Z'
            //System.out.println(i);
            //System.out.println((char) i);
            charArray[index] = (char) i;
            index++;
        }
        //When the loop ends, it means that A-Z has been stored in the array

        for (int i = 'a'; i <= 'z'; i++) {
            //i represents the number corresponding to the characters between 'A' and 'Z'
            //System.out.println(i);
            //System.out.println((char) i);
            charArray[index] = (char) i;
            index++;
        }

        //ergodic
        for (int i = 0; i < charArray.length; i++) {
            System.out.print(charArray[i] + " ");
        }
        System.out.println();


        Random r = new Random();
        //Repeat the above action four times.
        for (int i = 0; i < 4; i++) {
            //Gets a random character from the array
            //Get a random index
            int randomIndex = r.nextInt(charArray.length);
            //Obtain the corresponding element according to the random index
            char randomChar = charArray[randomIndex];
            System.out.print(randomChar);
        }

        //4. Regenerate into a random number between 0 and 9.
        int randomNumber = r.nextInt(10);
        System.out.print(randomNumber);
    }
}

8. Roll call device

Title:

Enter the number of classes with the keyboard, and enter the names of class students according to the number of classes

Take one randomly from the entered student names and print it on the console

Steps:

1. Enter the number of classes with the keyboard

2. Create an array according to the number of people entered on the keyboard

3. Store the student's name in the array

4. Get the random index of an array

5. Get the name through random index

6. Output name

answer:
public class Test9 {
    public static void main(String[] args) {
//        Enter the number of classes with the keyboard, and enter the names of class students according to the number of classes
//        Take one randomly from the entered student names and print it on the console

        //1. Enter the number of students in the class with the keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the number of students in the class");
        int studentCount = sc.nextInt();
        //2. Create an array according to the number of people.
            //Because the number of people is the length of the array.
        String [] arr = new String[studentCount];
        //3. Assign values to the array by keyboard entry
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Please enter the name of the class student");
            String name = sc.next();
            arr[i] = name;
        }
        System.out.println("-----------------------");

        //4. Randomly get a student's name from the array
        //Get a random index first
        //Then get the elements through this random index
        Random r = new Random();
        int randomIndex = r.nextInt(arr.length);// Writing arr.length in parentheses means that any index in the array is obtained randomly
                                                //Because this range has included all indexes in the array.
        //Gets the element based on the obtained random index
        String randomName = arr[randomIndex];
        //Output this random name
        System.out.println(randomName);


    }
}

9. The judges gave a score

Title:

In the programming competition, six judges score the contestants, and the scores are integers.

The final score of the contestant is the average value of the four judges after removing the highest score and the lowest score (regardless of the decimal part).

Steps:

1. Create an array with length of 6. Used to save the scores of 6 judges.

2. Enter the judges' scores on the keyboard and store them in the array.

3. Get the total score of the six judges.

4. Find the maximum value

5. Find the minimum value

6. Average score (total score - Maximum - Minimum) / 4

answer:
public class Test11 {
    public static void main(String[] args) {
        //In the programming competition, six judges score the contestants, and the scores are integers.
        //The final score of the contestant is the average value of the four judges after removing the highest score and the lowest score (regardless of the decimal part).


        //1. Create an array with length of 6.
        int[] arr = new int[6];
        //2. Enter the judges' scores on the keyboard and store them in the array
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Please enter the score of the judges");
            int score = sc.nextInt();
            //The scores entered on the keyboard are stored in the array
            arr[i] = score;
        }
        //When the loop ends, it indicates that the array is full of judges' scores
        //3. Sum all numbers in the array
        int sum = getSum(arr);
        //4. Find the maximum value
        int max = getMax(arr);
        //5. Seek the least wisdom
        int min = getMin(arr);

        //6. Average
        int avg = (sum - max - min) / (arr.length - 2);

        System.out.println("The player's final score is" + avg);

    }

    public static int getMin(int[] arr) {
        int min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (min > arr[i]) {
                min = arr[i];
            }
        }
        return min;
    }

    public static int getMax(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (max < arr[i]) {
                max = arr[i];
            }
        }
        return max;
    }


    public static int getSum(int[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum = sum + arr[i];
        }
        return sum;
    }
}

Keywords: Java

Added by ppgpilot on Sat, 11 Sep 2021 10:16:10 +0300