java daily exercise day01

Posted by halfman on Thu, 17 Feb 2022 13:23:30 +0100

1. Letter guessing game

  • 1. Randomly generate 5 letters - > character array
  • 2. Users guess letters - > console guess - > character array
  • 3. Compare the two character arrays, the correct number of letters and the correct number of positions
  • 4. The user guesses wrong and repeats 2 and 3
package day04.game;

import java.util.Arrays;
import java.util.Scanner;

/*
 * 1.Randomly generate 5 letters - > character array
 * 2.User guessing letters - > console guessing - > character array
 * 3.Compare the two character arrays, the correct number of letters and the correct number of positions
 * 4.The user guessed wrong and repeated 2 and 3
 */
public class GuessGame01Demo {
	public static void main(String[] args) {
		Scanner console = new Scanner(System.in);
		//1. Randomly generate 5 letters
		char[] charArr = randomChars();
		System.out.println(Arrays.toString(charArr));
		//4. The user guesses wrong and repeats 2 and 3
		while(true) {
			//2. Users guess letters
			System.out.println("Please enter:");
			String str = console.next();
			char[] guess = parseChars(str);
			//3. Compare charArr and guess character arrays
			int[] res = compare(charArr,guess);
			System.out.print("Correct number of letters:" + res[0]);
			System.out.println("Number of correct positions:" + res[1]);
			//Guess all
			if(res[1] == 5) {
				System.out.println("All right!");
				break;
			}
		}
		
	}
	
	/*
	 * Purpose: To compare two character arrays
	 */
	public static int[] compare(char[] answer, char[] guess) {
		// result[0] indicates the correct letter and result[1] indicates the correct position
		int[] result = new int[2];
		for(int i = 0; i < answer.length; i++) {
			for(int j = 0; j < guess.length; j++) {
				//Determine the correct number of letters
				if(answer[i] == guess[j]) {
					//If the letter is correct + 1
					result[0]++;
					//Number of correct positions
					if(i == j) {
						//If the position is correct + 1
						result[1]++;
					}
				}
			}
		}
		return result;
	}
	
	/*
	 * Purpose: to convert a string into a character array
	 */
	public static char[] parseChars(String str) {
		char[] charArr = new char[5];
		for(int i = 0; i < charArr.length; i++) {
			 charArr[i]= str.charAt(i);
		}
		return charArr;
	}
	
	
	/*
	 * Objective: to obtain a random character array with length of 5
	 */
	public static char[] randomChars() {
		char[] chars = new char[5];
		for(int i = 0; i < chars.length; i++) {
			chars[i] = (char)(Math.random() * 26 + 'A');
			for(int j = 0; j < i; j++) {
				//Judge whether the characters in position I are compared with all characters before position i
				if(chars[j] == chars[i]) {
					i--;//Return to the original position and regenerate the characters randomly
					break;//If it's the same, it's over
				}
			}
		}	
		return chars;
	}

}

Common API s - all classes
Scanner
nextInt()
nextDoble()
next(): get the string, encounter a space or enter to end
nextLine(): get a line of string and end with carriage return
System
print(): print without line breaks
println() line feed printing
Math
Math.random(): obtain the random value of [0,1]
Math.pow(double d1, double d2): obtain the d2 power of d1
String
str.charAt(index); Get the character corresponding to the index
Arrays
Arrays.toString(): read array
Arrays.sort(): sort the array

Sorting of arrays
Selection sorting: the largest one will be selected in each round and placed at the end
Bubble sorting: each round compares two adjacent elements, the small one in the front and the large one in the back
Insert sort: divide the array into two parts. The first part has been arranged, and the other part is accessed one by one. Insert the accessed elements into the appropriate position of the previous part
1234 8590

Bubble sorting principle analysis:
Array: [9, 7, 3, 6, 1] length = 5

i: int i = 0; i < length - 1; i++
j: int j = 0; j < length - 1 - i; j++

First round: I = 0 arr [J] > arr [J + 1]
7, 9, 3, 6, 1 j = 0 arr[0] arr[1] exchange
7, 3, 9, 6, 1 j = 1 arr[1] arr[2]
7, 3, 6, 9, 1 j = 2 arr[2] arr[3]
7, 3, 6, 1, 9 j = 3 arr[3] arr[4]

Second round: i = 1
3, 7, 6, 1, 9 j = 0
3, 6, 7, 1, 9 j = 1
3, 6, 1, 7, 9 j = 2

Third round: i = 2
3, 6, 1, 7, 9 j = 0
3, 1, 6, 7, 9 j = 1

Fourth round: i = 3
1, 3, 6, 7, 9 j = 0

package day04;

import java.util.Arrays;

/*Bubble sorting*/
public class Bubble {
    public static void main(String[] args) {
        int [] arr=new int[]{9,7,3,6,1};
        int[] arrs=bubblesort(arr);
        System.out.println(Arrays.toString(arrs));
    }
    public static int[] bubblesort(int [] arr){
        for (int i = 0; i <arr.length-1 ; i++) {
            for (int j = 0; j <arr.length-1-i ; j++) {
                if (arr[j]>arr[j+1]){
                    int temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }

            }

        }
        return arr;
    }
}

Selection sorting: the largest one will be selected in each round and placed at the end
Array: [9, 7, 3, 6, 1] length = 5

First round: 1, 7, 3, 6, 9
int index = 0;
1: Compare arr[1] and arr[index], and record the maximum subscript index = 0
2: Compare arr[2] and arr[index]. If arr[2] is large, replace it, and record the maximum subscript index = 0
3: Compare arr[3] and arr[index]. If arr[3] is large, replace it, and record the maximum subscript index = 0
4: Compare arr[4] and arr[index]. If arr[4] is large, replace it, and record the maximum subscript index = 0
index is exchanged with the current last bit (length - 1)
i:0
j: 1 ~ 4

Second round: 1, 6, 3, 7, 9
1: Compare arr[0] and arr[1], and record the maximum subscript index = 1
2: Compare arr[2] and arr[index]. If arr[2] is large, replace it, and record the maximum subscript index = 1
3: Compare arr[3] and arr[index]. If arr[3] is large, replace it, and record the maximum subscript index = 1
index is exchanged with the current last bit (length -1 -1)

i: 1
j: 1 ~ 3

Third round: 1, 3, 6, 7, 9
1: Compare arr[0] and arr[1], and record the maximum subscript index = 1
2: Compare arr[2] and arr[index]. If arr[2] is large, replace it, and record the maximum subscript index = 1
index and the current last bit (length -1 -2) are exchanged
i: 2
j: 1 ~ 2

Fourth round: 1, 3, 6, 7, 9
1: Compare arr[0] and arr[1], and record the maximum subscript index = 1
index and the current last bit (length -1 -3) are exchanged

i: 3
j: 1

i: int i = 0; i < legth - 1; i++
j: int j = 1; j < length - i; j++
Current last bit: length - 1 -i

package day04;

import java.util.Arrays;

/*Select sort*/
public class Select {
    public static void main(String[] args) {
        int[] arr={9,7,3,8,1};
        selectSort(arr);
        System.out.println(Arrays.toString(arr));

    }
    public static void selectSort(int[] arr){
        
        for (int i = 0; i <arr.length-1 ; i++) {
            int index=0;
            for (int j = 1; j <arr.length-i ; j++) {
                if (arr[j]>arr[index]){
                    index=j;//Assign j to index
                }
                //change of position
                int temp=arr[index];
                arr[index]=arr[arr.length-1-i];
                arr[arr.length-1-i]=temp;

            }

        }
    }
}

Topics: JavaSE