java - 我无法打印我的数组

标签 java arrays arraylist

我尝试使用 Arrays.toString(array)); 打印我的数组但它仍然给了我错误...而且 ELEMENT IS FOUND 是错误的语句,但当我尝试搜索数组中的元素时,它与正确的语句混合, 例如......

I searched 4 in my array: 4 , 2, 3 ,5

但“找到元素”仍然显示。

import java.util.Scanner;

public class linee {
    public static void main(String[] args) {
        int String;
        int value;
        Scanner in = new Scanner(System.in);
        System.out.print("Input the Number of Element: ");
        String n = in.nextLine();
        int num = Integer.parseInt(n);
        String array[] = new String[num];
        for (int i = 0; i < array.length; i++) {
            System.out.print("Input the Number at array index " + i + ": ");
            array[i] = in.nextLine();
        }
        Linear(array);
        System.out.print("\nDo you want to continue? YES = 1, NO = 2: ");
        value = in.nextInt();
        if (value == 1) {
            main(args);
        } else if (value == 2) {
            System.out.println("\nThank you for using the program.");
        }
    }

    public static void Linear(String[] array) {
        boolean flag = false;
        String key = "";
        int index = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number that you want to search: ");
        key = in.nextLine();
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(key)) {
                flag = true;
                index = i;
            }
        }
        if (flag == true) {
            System.out.println("Elements: " + Arrays.toString(array));
            System.out.println("ELEMENT IS FOUND AT INDEX " + index);
        } else {
            System.out.println("ELEMENT IS NOT FOUND");
        }
    }
}

最佳答案

来自Object.toString(Object[] a)规范:

Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.

也就是说,您可能想以另一种方式打印您的元素。一个选项是:

System.out.println("Elements: ");
for(String str: array) {
    System.out.println(str);
}

关于java - 我无法打印我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479536/

相关文章:

c++ - 随机生成一个没有重复元素的枚举数组(C++)

java - java中x数据类型数组占用的实际大小(以字节为单位)?

java - 在数组中搜索缺失数字时的性能

java - 如何每 3 次点击而不是每次广告关闭时重新加载广告?

javascript - 当字符串位于数组中时,返回 JavaScript 中的长度字符串

java - 在将相同的元素添加到新的 ArrayList 后,有什么方法可以从给定的 ArrayList 中删除某些元素吗?

java - 如何在泛型类中设置随机值

java - DBsetup 后 Spring 数据不增加

java - 从一项 Activity 转移到另一项 Activity 时,静态变量会重新初始化自身

java - 如何从文件中读取 N 行?