我正在尝试打印我的 Athlete 类、国家和姓名中两个数组的第一个元素。我还需要创建一个对象来模拟运动员进行的三次跳水尝试(最初设置为零)。我是 OOP 的新手,我不知道如何在我的主要方面做这件事……就构造函数而言。这是我到目前为止所做的......
这是主要的:
import java.util.Random;
import java.util.List;
public class Assignment1 {
public static void main(String[] args) {
Athlete art = new Athlete(name[0], country[0], performance[0]);
}
}
我真的不知道该怎么办...
这是带有数组的类。
import java.util.Random;
import java.util.List;
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
//Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.)
Athlete(String[] name, String[] country, Performance[] performance) {
this.name = name;
this.country=country;
this.performance=performance;
}
public Performance Perform(Dive dive){
dive.getDiveName();
return null;
}
public String[] getName() {
return name;
}
public void setName(String[] name) {
this.name = name;
}
public String[] getCountry() {
return country;
}
public void setCountry(String[] country) {
this.country = country;
}
}
在此先感谢您的帮助和意见! 顺便说一句,还有其他类(class),只是不相关的 atm..
最佳答案
首先,对于你的 Athlete 类,你可以删除你的 Getter and Setter
方法,因为您已经使用 public
的访问修饰符声明了实例变量.您可以通过 <ClassName>.<variableName>
访问变量.
然而,如果你真的想使用那个Getter and Setter
, 更改 public
private
的修饰符反而。
其次,对于构造函数,您正在尝试执行一项名为 shadowing
的简单技术。 . Shadowing
是当您有一个方法具有与声明的变量同名的参数时。这是 shadowing
的示例:
----------Shadowing sample----------
您有以下类(class):
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
例如,在您的主要方法中,您实例化了 Person
类如下:
Person person = new Person("theolc");
变量 name
将等于 "theolc"
.
----------End of shadowing----------
让我们回到你的问题,如果你只想用你当前的代码打印第一个元素,你可以删除 Getter and Setter
.删除您的 constructor
上的参数.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
在您的主要方法中,您可以这样做。
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
关于java - Java 中的字符串数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420871/