gpt4 book ai didi

java - 数组列表的问题

转载 作者:行者123 更新时间:2023-12-02 00:27:01 25 4
gpt4 key购买 nike

我正在做一个项目,我认为数组列表会更好,而不是使用数组。我知道我需要声明数组列表及其方法,但我不太确定从哪里开始。有什么建议么?这是代码...

public class Student {

private String name;
private int[] tests;

public Student() {
this("");
}

public Student(String nm) {
this(nm, 3);
}

public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}

public Student(String nm, int[] t) {
tests = new int[t.length];
}

public Student(Student s) {
this(s.name, s.tests);
}

public int getNumberOfTests() {
return tests.length;
}

public void setName(String nm) {
name = nm;
}

public String getName() {
return name;
}

public void setScore(int i, int score) {
tests[i - 1] = score;
}

public int getScore(int i) {
return tests[i - 1];
}

public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}

public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}

public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}

public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}

最佳答案

I figured an array list would be better

也许吧。也许不会。这取决于。使用基于 ArrayList 的产品看起来您会受益吗? API?

如果您的“列表”永远不会改变大小,并且您不需要在其中查找内容,那么数组也同样好。

I know I need to declare the array list and its methods, but I am not too sure where to go from there

您需要创建对 ArrayList 实例的引用。就这么简单

List<Integer> myList = new ArrayList<Integer>();

在你的类声明中。您不需要“声明其方法”。当您拥有对对象的引用时,您可以调用其方法。

关于java - 数组列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9793727/

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