【问题标题】:Possible coding error[I@24e11c [duplicate]可能的编码错误[I@24e11c [重复]
【发布时间】:2014-03-18 18:34:06
【问题描述】:

我必须从一个外部文件中读取一个数字列表并将它们插入到自己的数组中,以确定它们是正数还是负数。扫描仪可以很好地读取数字,但是当将它们插入数组时就会出错。如您所见,下面是我的代码和输出。文件中的内容打印在输出中,但是当我要求它打印数组时,就是字母/数字/符号的混乱。谁能帮我修一下?

public class Numbers {
    public static void main(String[] args) throws IOException {
        Scanner reader = new Scanner(new FileInputStream("First.dat"));
        int Positive[] = new int[20];
        int Negative[] = new int[20];
        int X = 0;
        int Y = 0;
        while (reader.hasNextInt()) {
            int Start = reader.nextInt();
            System.out.println(Start);
            if (Start < 0) {
                Negative[X] = Start;
                X += 1;
            }
            if (Start > 0) {
                Positive[Y] = Start;
                Y += 1;
            }

        }
        System.out.println(Positive + "  " + Negative);
    }
}

输出:

3
66
54
-8
22
-16
-56
19
21
34
-34
-22
-55
-3
-55
-76
64
55
9
39
54
33
-45
[I@1b41650  [I@24e11c

【问题讨论】:

  • 您希望它打印什么?为什么?
  • 我希望它打印出我插入数字的数组
  • 想要 如果您不知道自己在做什么,则无关紧要。你做了什么,你为什么要这样做?你为什么不做点别的?

标签: java


【解决方案1】:

您将看到将数组直接转换为String 的结果。数组也是对象,但它们不会覆盖 Object's toString() 方法,这是造成“混乱”的原因。

换句话说,这个方法返回一个等于值的字符串:

getClass().getName() + '@' + Integer.toHexString(hashCode())

使用Arrays.toString 将数组的内容显式转换为String

System.out.println(Arrays.toString(Positive) + "  " + Arrays.toString(Negative));

【讨论】:

  • 成功了,感谢您的帮助!
【解决方案2】:

您看到的是数组的对象引用。要按照您显然期望的方式打印出数组的内容,请使用Arrays.toString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多