Java from entry to proficiency - array (3)

0. array

![Insert image description here](https://img-blog.csdnimg.cn/1fbcd1668f4d42bf90e134d8d7bf2931.png

1. Array overview

Exercise 1:  Create an integer array to store your favorite 5 numbers and write code to print out these numbers.

Create an array of integers

public class Main {
    public static void main(String[] args) {
        // 创建一个整数数组,存储5个喜欢的数字
        int[] favoriteNumbers = {7, 22, 14, 42, 3};

        // 打印出这些数字
        System.out.println("我喜欢的数字:");
        for (int i = 0; i < favoriteNumbers.length; i++) {
            System.out.println(favoriteNumbers[i]);
        }
    }
}

case analysis:

  1. In this exercise, we first created an  favoriteNumbers integer array called , which contained 5 of our favorite numbers.
  2. Use  for a loop to iterate over the array, access each element in the array by index, and  System.out.println() print them out using a method.

Summary:

  • An array is a data structure used to store a set of elements of the same data type that can be accessed sequentially.
  • When creating an array, we need to specify the type and length of the array, and can initialize the elements of the array through an initializer list.
  • Traversing an array is accomplished by looping, usually using  for a loop or enhanced  for-each loop to access the elements in the array.
  • Array is one of the common data structures in Java, used to store and process large amounts of data. In this example, we successfully created an array of integers and printed the elements in the array. This is a simple example from the array overview that helps us understand the basic concepts and usage of arrays.

2. One-dimensional array

Exercise 2:  Create an array of strings containing the names of some fruits, and then use a loop to loop through and print the names of the fruits in the array.

Create an array of strings and iterate over print

public class Main {
    public static void main(String[] args) {
        // 创建一个字符串数组,包含一些水果的名称
        String[] fruits = {"苹果", "香蕉", "橙子", "葡萄", "樱桃"};

        // 使用循环遍历并打印数组中的水果名称
        System.out.println("水果列表:");
        for (int i = 0; i < fruits.length; i++) {
            System.out.println(fruits[i]);
        }
    }
}

case analysis:

  1. In this exercise, we first create a  fruits string array named which contains the names of some fruits.
  2. Use  for a loop to iterate over the array, access each element in the array by index, and  System.out.println() print them out using a method.

Summary:

  • An array is a data structure used to store a set of elements of the same data type that can be accessed sequentially.
  • In this example, we create an array of strings to store the names of fruits.
  • Iterating over an array using a loop is a common operation. You can use  for a loop or an enhanced  for-each loop to access the elements in an array.
  • Arrays are very useful in many programming scenarios, they allow us to store and process multiple data elements efficiently.
  • In this example, we have successfully created a string array and printed the names of the fruits in the array, which helps to understand the basic usage of the array.

Exercise 3:  Write a program that accepts a set of numbers entered by the user and then calculates their average.

Calculate the average of a set of numbers

import java.util.Scanner;

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

        // 提示用户输入一组数字
        System.out.print("请输入一组数字,以空格分隔:");
        String input = scanner.nextLine();

        // 使用空格分割输入字符串,将数字存储到数组中
        String[] numbersAsString = input.split(" ");
        double[] numbers = new double[numbersAsString.length];

        for (int i = 0; i < numbersAsString.length; i++) {
            numbers[i] = Double.parseDouble(numbersAsString[i]);
        }

        // 计算数字的平均值
        double sum = 0;
        for (double number : numbers) {
            sum += number;
        }

        double average = sum / numbers.length;

        // 打印平均值
        System.out.println("这组数字的平均值是:" + average);

        // 关闭Scanner
        scanner.close();
    }
}

case analysis:

  1. In this exercise, we first use  Scanner a class to accept input from the user, asking the user to enter a set of numbers, separated by spaces.
  2. The input string is split into an array of numeric strings and converted to  double an array of type through a loop.
  3. We calculate the sum of the numbers and then calculate the average by dividing by the number of numbers.
  4. Finally, we print out the calculated average.

Summary:

  • This example demonstrates how to use an array in Java to store a set of numbers and how to calculate the average of these numbers.
  • Scanner Class is used to accept user input,  split() split the input string into an array through methods, and then convert the string into numbers through a loop.
  • Arrays are a powerful tool that help organize and process large amounts of data, and they allow us to perform various mathematical and statistical calculations.
  • Through this exercise, readers can learn how to handle user input and use arrays to perform basic mathematical operations.

3. Two-dimensional array

Exercise 4:  Create a two-dimensional integer array to represent the initial state of a nine-square Sudoku game, and write code to print out the initial state of the Sudoku.

Create and print the initial state of the Jiugongge Sudoku game

public class Main {
    public static void main(String[] args) {
        // 创建一个二维整数数组来表示数独游戏的初始状态
        int[][] sudoku = {
            {5, 3, 0, 0, 7, 0, 0, 0, 0},
            {6, 0, 0, 1, 9, 5, 0, 0, 0},
            {0, 9, 8, 0, 0, 0, 0, 6, 0},
            {8, 0, 0, 0, 6, 0, 0, 0, 3},
            {4, 0, 0, 8, 0, 3, 0, 0, 1},
            {7, 0, 0, 0, 2, 0, 0, 0, 6},
            {0, 6, 0, 0, 0, 0, 2, 8, 0},
            {0, 0, 0, 4, 1, 9, 0, 0, 5},
            {0, 0, 0, 0, 8, 0, 0, 7, 9}
        };

        // 打印数独的初始状态
        System.out.println("数独的初始状态:");
        printSudoku(sudoku);
    }

    // 辅助方法:打印数独
    public static void printSudoku(int[][] sudoku) {
        for (int i = 0; i < sudoku.length; i++) {
            for (int j = 0; j < sudoku[i].length; j++) {
                System.out.print(sudoku[i][j] + " ");
            }
            System.out.println();
        }
    }
}

case analysis:

  1. In this exercise, we create a  sudoku two-dimensional array of integers called , which represents the initial state of the Sudoku game. 0 in the array represents a space, and other numbers represent known numbers.
  2. We use  printSudoku the method to print the initial state of the sudoku. This method traverses the two-dimensional array through nested loops, and prints the Sudoku grid line by line.

Summary:

  • Arrays are a powerful tool for storing and manipulating multidimensional data. In this example, we use a two-dimensional array of integers to represent the initial state of the Sudoku game.
  • Use nested loops to efficiently iterate over all elements of a 2D array and manipulate them as desired.
  • Sudoku is a classic math puzzle, and through this exercise, the reader learns how to use arrays to represent and manipulate the state of the game

Exercise 5:  Write a program that generates a 3x3 random maze map that includes a starting point, an ending point, and walls.

Generate random maze map

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        // 定义迷宫地图的大小
        int rows = 3;
        int cols = 3;

        // 创建一个二维字符数组来表示迷宫地图
        char[][] maze = generateMaze(rows, cols);

        // 打印迷宫地图
        System.out.println("随机生成的迷宫地图:");
        printMaze(maze);
    }

    // 辅助方法:生成随机迷宫地图
    public static char[][] generateMaze(int rows, int cols) {
        char[][] maze = new char[rows][cols];
        Random random = new Random();

        // 随机设置起点、终点和墙壁
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int randomNumber = random.nextInt(3); // 生成0到2之间的随机数
                if (randomNumber == 0) {
                    maze[i][j] = 'S'; // 起点
                } else if (randomNumber == 1) {
                    maze[i][j] = 'E'; // 终点
                } else {
                    maze[i][j] = '#'; // 墙壁
                }
            }
        }

        return maze;
    }

    // 辅助方法:打印迷宫地图
    public static void printMaze(char[][] maze) {
        for (int i = 0; i < maze.length; i++) {
            for (int j = 0; j < maze[i].length; j++) {
                System.out.print(maze[i][j] + " ");
            }
            System.out.println();
        }
    }
}

case analysis:

  1. In this exercise, we define the size of the maze map and create a two-dimensional character array  maze to represent the maze map.
  2. Use  Random classes to generate random start, end, and walls. We determine the elements on the map by generating a random number between 0 and 2, where 0 represents the starting point, 1 represents the end point, and 2 represents the wall.
  3. Finally, we  printMaze print the generated maze map through the method.

Summary:

  • This example demonstrates how to generate a random maze map using a two-dimensional character array in Java.
  • Random Class used to generate random numbers to help create different maze maps.
  • Arrays are often used to represent complex scenes and states in applications such as game development, map generation, and simulation.
  • Through this exercise, readers can learn how to use arrays to construct randomly generated maze maps, which helps to understand the application of arrays in game programming.

4. Basic operations on arrays

Exercise 6:  Write a program that accepts a set of numbers entered by the user and finds the maximum and minimum values.

Find the maximum and minimum value of a set of numbers

import java.util.Scanner;

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

        // 提示用户输入一组数字,以空格分隔
        System.out.print("请输入一组数字,以空格分隔:");
        String input = scanner.nextLine();

        // 使用空格分割输入字符串,将数字存储到数组中
        String[] numbersAsString = input.split(" ");
        double[] numbers = new double[numbersAsString.length];

        for (int i = 0; i < numbersAsString.length; i++) {
            numbers[i] = Double.parseDouble(numbersAsString[i]);
        }

        // 查找最大值和最小值
        double max = findMax(numbers);
        double min = findMin(numbers);

        // 打印最大值和最小值
        System.out.println("最大值是:" + max);
        System.out.println("最小值是:" + min);

        // 关闭Scanner
        scanner.close();
    }

    // 辅助方法:查找数组中的最大值
    public static double findMax(double[] numbers) {
        double max = numbers[0];
        for (double number : numbers) {
            if (number > max) {
                max = number;
            }
        }
        return max;
    }

    // 辅助方法:查找数组中的最小值
    public static double findMin(double[] numbers) {
        double min = numbers[0];
        for (double number : numbers) {
            if (number < min) {
                min = number;
            }
        }
        return min;
    }
}

case analysis:

  1. In this exercise, we use  Scanner a class to accept input from the user, asking the user to enter a set of numbers, separated by spaces.
  2. The input string is split into an array of numeric strings and converted to  double an array of type through a loop.
  3. We write two helper methods  findMax and  findMin to find the maximum and minimum values ​​in the array respectively.
  4. Finally, we print out the maximum and minimum values ​​found.

Summary:

  • This example demonstrates how to use Java to find the maximum and minimum value of a set of numbers.
  • Scanner Class is used to accept user input,  split() split the input string into an array through methods, and then convert the string into numbers through a loop.
  • Arrays are a tool that facilitates the storage and manipulation of multiple data elements and can be used in various mathematical and statistical calculations.
  • Through this exercise, readers can learn how to process user input and use arrays to perform basic mathematical operations, such as finding maximum and minimum values.

Exercise 7:  Create two integer arrays representing the coordinates of two vectors, and then write code to calculate the dot product (inner product) of these two vectors.

Compute the dot product of two vectors

public class Main {
    public static void main(String[] args) {
        // 创建两个整数数组,分别表示两个向量的坐标
        int[] vector1 = {2, 3, -1};
        int[] vector2 = {1, -2, 2};

        // 计算两个向量的点积
        int dotProduct = calculateDotProduct(vector1, vector2);

        // 打印点积结果
        System.out.println("两个向量的点积是:" + dotProduct);
    }

    // 辅助方法:计算两个向量的点积
    public static int calculateDotProduct(int[] vector1, int[] vector2) {
        if (vector1.length != vector2.length) {
            throw new IllegalArgumentException("向量长度不一致");
        }

        int dotProduct = 0;
        for (int i = 0; i < vector1.length; i++) {
            dotProduct += vector1[i] * vector2[i];
        }

        return dotProduct;
    }
}

case analysis:

  1. In this exercise, we first created two integer arrays  vector1 and  vector2, which represent the coordinates of the two vectors, respectively.
  2. We wrote a helper method  calculateDotProduct to compute the dot product of two vectors.
  3. The calculation of the dot product is obtained by traversing the coordinates of the two vectors and multiplying them accordingly.

Summary:

  • This example demonstrates how to calculate the dot product (inner product) of two vectors using Java.
  • The helper method  calculateDotProduct accepts two integer arrays, first checks whether their lengths are consistent, and then calculates the dot product.
  • Arrays are a tool that facilitates vector and matrix operations, which are commonly used in calculations in the fields of linear algebra and mathematics.
  • Through this exercise, readers can learn how to use arrays to perform vector operations and how to write and call custom helper methods.

5. Array arrangement algorithm

Exercise 8:  Use bubble sort or selection sort to sort an integer array in ascending order and print the sorted array.
The following is an example of answering Exercise 8 in the "Array Sorting Algorithms" module using Java, using the bubble sort algorithm, and includes explanation and summary:

Sort integer array in ascending order using bubble sort

public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 9, 1, 5, 6};

        System.out.println("排序前的数组:");
        printArray(numbers);

        // 使用冒泡排序算法对数组进行升序排列
        bubbleSort(numbers);

        System.out.println("排序后的数组:");
        printArray(numbers);
    }

    // 冒泡排序算法
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        boolean swapped;

        for (int i = 0; i < n - 1; i++) {
            swapped = false;

            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // 交换arr[j]和arr[j+1]的位置
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }

            // 如果内循环没有发生交换,表示数组已排序完成,可以提前退出
            if (!swapped) {
                break;
            }
        }
    }

    // 打印数组
    public static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

case analysis:

  1. In this exercise, we first create an integer array  numberscontaining some unsorted integers.
  2. Use the bubble sort algorithm to sort the array in ascending order, and the sorted array will overwrite the original array.
  3. The core idea of ​​the bubble sort algorithm is to sequentially compare adjacent elements and exchange them, and gradually move larger elements to the right.
  4. We use  printArray methods to print the array before and after sorting.

Summary:

  • This example demonstrates how to implement the bubble sort algorithm in Java to sort an array of integers in ascending order.
  • Bubble sort is a simple but inefficient sorting algorithm that sequentially compares adjacent elements and swaps them until the array is completely sorted.
  • Bubble sort works well for small data sets, but performs poorly on large data sets.
  • Through this exercise, readers can learn the basic principles and implementation of sorting algorithms, and how to apply them to sort arrays.

Exercise 9:  Write a program that generates an array of 10 random integers and sorts it using the quicksort algorithm.
The following is an example of answering Exercise 9 in the "Array Sorting Algorithms" module using Java, using the quicksort algorithm, and includes an explanation and summary:

Sort an array of 10 random integers using quick sort

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int[] numbers = generateRandomArray(10);

        System.out.println("排序前的数组:");
        printArray(numbers);

        // 使用快速排序算法对数组进行升序排列
        quickSort(numbers, 0, numbers.length - 1);

        System.out.println("排序后的数组:");
        printArray(numbers);
    }

    // 快速排序算法
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, low, high);

            // 递归排序左半部分和右半部分
            quickSort(arr, low, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, high);
        }
    }

    // 快速排序的分区函数
    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                // 交换arr[i]和arr[j]的位置
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // 交换arr[i+1]和arr[high]的位置,将pivot放到正确的位置
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    // 生成包含n个随机整数的数组
    public static int[] generateRandomArray(int n) {
        int[] arr = new int[n];
        Random random = new Random();

        for (int i = 0; i < n; i++) {
            arr[i] = random.nextInt(100); // 生成0到99之间的随机整数
        }

        return arr;
    }

    // 打印数组
    public static void printArray(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

case analysis:

  1. In this exercise, we first generate an array containing 10 random integers  numbers.
  2. quickSort Sort the array in ascending order using quicksort algorithm  .
  3. The core idea of ​​the quick sort algorithm is to select a reference element (the last element is selected here), divide the array into two parts, the left part is smaller than the reference element, and the right part is larger than the reference element, and then recursively sort the left and right parts.
  4. We use  generateRandomArray methods to generate random arrays and  printArray methods to print the pre-sorted and post-sorted arrays.

Summary:

  • This example demonstrates how to implement the quick sort algorithm in Java to sort an array containing random integers in ascending order.
  • Quick sort is an efficient sorting algorithm with an average time complexity of O(nlogn).
  • The key to quick sort is the partition process, which divides the array into two parts and sorts them recursively until the entire array is sorted.
  • Through this exercise, readers can learn the efficiency of sorting algorithms and the application of recursive algorithms.

6. Practice and Exercise

Exercise 10:  Create a simple task management program that uses arrays to store task descriptions and status (unfinished/completed) and provides options to add, view, and mark the status of tasks.

import java.util.Scanner;

public class TaskManager {
    private static final int MAX_TASKS = 100; // 最大任务数量
    private String[] tasks; // 存储任务的描述
    private boolean[] taskStatus; // 存储任务的状态,true表示已完成,false表示未完成
    private int taskCount; // 任务数量

    public TaskManager() {
        tasks = new String[MAX_TASKS];
        taskStatus = new boolean[MAX_TASKS];
        taskCount = 0;
    }

    // 添加新任务
    public void addTask(String description) {
        if (taskCount < MAX_TASKS) {
            tasks[taskCount] = description;
            taskStatus[taskCount] = false; // 默认设置为未完成
            taskCount++;
            System.out.println("任务已添加!");
        } else {
            System.out.println("任务列表已满,无法添加新任务。");
        }
    }

    // 查看任务列表
    public void viewTasks() {
        if (taskCount == 0) {
            System.out.println("任务列表为空。");
        } else {
            System.out.println("任务列表:");
            for (int i = 0; i < taskCount; i++) {
                String status = taskStatus[i] ? "[已完成]" : "[未完成]";
                System.out.println(status + " " + (i + 1) + ". " + tasks[i]);
            }
        }
    }

    // 标记任务状态
    public void markTaskCompleted(int index) {
        if (index >= 1 && index <= taskCount) {
            taskStatus[index - 1] = true;
            System.out.println("任务已标记为已完成。");
        } else {
            System.out.println("无效的任务索引。");
        }
    }

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

        while (true) {
            System.out.println("任务管理程序选项:");
            System.out.println("1. 添加新任务");
            System.out.println("2. 查看任务列表");
            System.out.println("3. 标记任务为已完成");
            System.out.println("4. 退出程序");
            System.out.print("请选择操作(1/2/3/4):");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    System.out.print("请输入任务描述:");
                    String description = scanner.nextLine();
                    taskManager.addTask(description);
                    break;
                case 2:
                    taskManager.viewTasks();
                    break;
                case 3:
                    System.out.print("请输入要标记为已完成的任务索引:");
                    int index = scanner.nextInt();
                    taskManager.markTaskCompleted(index);
                    break;
                case 4:
                    System.out.println("程序已退出。");
                    scanner.close();
                    System.exit(0);
                default:
                    System.out.println("无效的选项,请重新选择。");
                    break;
            }
        }
    }
}

case analysis:

  1. This example creates a  TaskManager task manager class called , using an array to store the description and status (incomplete/completed) of the tasks.
  2. Users have options to add new tasks, view the task list, and mark task status.
  3. The main program part uses an infinite loop, and the user can choose different operations according to the prompts.
  4. Use  Scanner classes to accept user input.

Summary:

  • This example demonstrates how to use Java to create a simple task management program, which uses arrays to store task information and provide basic operation options.
  • Arrays are used in this program to store task descriptions and status, and the functionality can be easily extended to meet more complex needs.
  • Through this exercise, readers can learn how to use arrays and basic control structures to create a small command-line program, which helps to understand the use of arrays in practical applications.

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132792457