dev*_*ger 1 java arrays multidimensional-array
嗨,
我是Java新手并试图找出如何将这些数据推入数组(6行,3列)?
x1 John 6
x2 Smith 9
x3 Alex 7
y1 Peter 8
y2 Frank 9
y3 Andy 4
Run Code Online (Sandbox Code Playgroud)
之后,我将从最后一栏获取数字进行数学计算.
这是我的代码......
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();
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个作为输出......
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
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
Person [] people = new Person[10];
people[0] = new Person("x1", "John", 6);
...
Run Code Online (Sandbox Code Playgroud)
或者更好地使用java.util.List而不是阵列.
现场访问
要访问单独的字段,您需要将字段设为公共(非常糟糕的想法)并简单地将它们称为object_instance.field_name,或者提供所谓的getter:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public int getAnotherNumber() {
return anotherNumber;
}
}
Run Code Online (Sandbox Code Playgroud)
打印时调用它:
for (int i = 0; i < mass.length; i++) {
System.out.print(mass[i].getAnotherNumber() + " ");
}
Run Code Online (Sandbox Code Playgroud)
你为什么尝试不起作用:
System.out.println(mass[0])在您的情况下将打印整个对象表示,默认情况下它会打印它在您的情况下执行的操作.要做得更好,你需要覆盖Object的String toString()方法:
class Person {
String id;
String name;
int anotherNumber;
// constructor, getters, setters
public String toString() {
return "{id="+id+", name="+name+", anotherNumber="+anotherNumber+"}";
}
}
Run Code Online (Sandbox Code Playgroud)