在 java 中打印数组的特定部分

print specific part of an array in java

我想打印一个数组的一部分,其中一个数字作为该数组的末尾给出。 这很难用语言来解释,所以让我开门见山。 假设我有一个数组 {1,...,6,...,9}。我只想从 1 到 6 return 个元素。 这些数字不是索引,它们是实际值。

示例输入:

当然,如果作为参数给出的数字不在 arr 中,它将 return 出错。

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int arr[] = {1,2,3,11,6,8,12};
        int value = 6;
        
        System.out.println("Input: " + Arrays.toString(arr));

        // primitive way
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
            if (arr[i] == value) {
                System.out.print("Now stop");
                break;
            }
        }

        // What I need:
        arr = cut(arr, 6);

        System.out.println();
        System.out.println("Output: " + Arrays.toString(arr));
    }

    public static int[] cut(int[] arr, int value) {
        // Best way in Java to reduce the array?

        return arr;
    }
}
Input: [1, 2, 3, 11, 6, 8, 12]
1 2 3 11 6 Now stop
Output: [1, 2, 3, 11, 6, 8, 12] <- should be [1, 2, 3, 11, 6]

您需要确定您的值在数组中的位置。 然后您可以将子数组从起始索引带到该位置。 加一以包括搜索值。

不幸的是,数组没有 indexOf 方法,Arrays.binarySearch 仅适用于排序数组。也没有Arrays.search

因此,我们需要将数组转换为列表来使用indexOf,或者我们需要通过索引迭代数组,直到找到搜索值。

没有List<int>。因此我们需要将元素从 int 转换为 Integer。因此,boxed 操作。

最后,使用列表不值得,但它是一个有趣的练习!

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        int arr[] = {1,2,3,11,6,8,12};
        int value = 6;
        
        System.out.println("Input:  " + Arrays.toString(arr));
        arr = cut(arr, 6);
        System.out.println("Output: " + Arrays.toString(arr));
    }

    public static int[] cut(int[] arr, int value) {
        int position = Arrays.stream(arr) // turn into stream
                        .boxed() // turn elements into class Integer 
                        .collect(Collectors.toList()) // turn into list
                        .indexOf(value); // find position with list operation
        return Arrays.copyOfRange(arr, 0, position + 1);
    }
}

瞧瞧:

Input:  [1, 2, 3, 11, 6, 8, 12]
Output: [1, 2, 3, 11, 6]