gpt4 book ai didi

java - 如何组织不同类型的数组?

转载 作者:行者123 更新时间:2023-11-29 09:38:10 25 4
gpt4 key购买 nike

嗨,

我是 Java 的新手,正在尝试弄清楚如何将这些数据推送到数组(6 行,3 列)中?

x1 John 6
x2 Smith 9
x3 Alex 7
y1 Peter 8
y2 Frank 9
y3 Andy 4

之后,我将从最后一栏中提取数字进行数学计算。

这是我的代码...

public class Testing {
public static void main(String[] args) {

Employee eh = new Employee_hour();

Employee_hour [] eh_list = new Employee_hour[6];
eh_list[0] = new Employee_hour("x1", "John", 6);
eh_list[1] = new Employee_hour("x2", "Smith", 9);
eh_list[2] = new Employee_hour("x3", "Alex", 7);
eh_list[3] = new Employee_hour("y1", "Peter", 8);
eh_list[4] = new Employee_hour("y2", "Frank", 9);
eh_list[5] = new Employee_hour("y3", "Andy", 4);
print(eh_list);
}

private static void print(Employee_hour[] mass){
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i] + " ");
}
System.out.println();
}
}

但是我得到这个作为输出...

testing.Employee_hour@1a752144 testing.Employee_hour@7fdb04ed testing.Employee_hour@420a52f testing.Employee_hour@7b3cb2c6 testing.Employee_hour@4dfd245f testing.Employee_hour@265f00f9

如何从最后一列中获取数字?

最佳答案

为什么不为您的记录创建一个特定的 Java bean?

class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
}

然后像这样使用它:

Person [] people = new Person[10];
people[0] = new Person("x1", "John", 6);
...

或者更好的是使用 java.util.List 而不是数组。

现场访问

为了访问单独的字段,您需要公开您的字段(非常糟糕的主意)并简单地将它们称为 object_instance.field_name,或者提供所谓的 getter:

class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters

public int getAnotherNumber() {
return anotherNumber;
}
}

然后在打印的时候调用:

for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i].getAnotherNumber() + " ");
}

为什么您尝试的方法不起作用:

System.out.println(mass[0]) 在您的案例中将打印整个对象表示,默认情况下它会打印它在您的案例中所做的事情。为了做得更好,您需要覆盖 ObjectString toString() 方法:

class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters

public String toString() {
return "{id="+id+", name="+name+", anotherNumber="+anotherNumber+"}";
}
}

关于java - 如何组织不同类型的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11117719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com