在 main 的末尾有一個方法呼叫,它呼叫了一個 String 方法。我最初的計劃是從 Roster 創建一個陣列參考,然后只復制其中沒有 Stern 的元素。
我最終只是這樣做,清除了 .roster,然后將元素從一個陣列復制到另一個陣列,但它仍然回傳相同的 roster 計數 4。此時我不確定如何繼續前進,希望得到一些指導。一定要意識到代碼、方法等是不能改變的。唯一可以改變的是方法中的內容。丟學生()。
包學習3;
匯入 java.util.ArrayList;
public class Course {
private ArrayList<Student> roster; // Collection of Student objects
public Course() {
roster = new ArrayList<Student>();
}
// Drops a student from course by removing student from course roster
public void dropStudent(String last) {
ArrayList<Student> nonDropList = new ArrayList<>();
// while (!press.equals("q")) {
for (Student nondrop: roster) {
if (!nondrop.getLast().equals(last)) {
nonDropList.add(nondrop);
}
}
roster = new ArrayList(nonDropList);
}
public void addStudent(Student s) {
roster.add(s);
}
public int countStudents() {
return roster.size();
}
// main
public static void main(String args[]) {
Course course = new Course();
String first; // first name
String last; // last name
double gpa; // grade point average
int beforeCount;
first = "Henry";
last = "Nguyen";
gpa = 3.5;
course.addStudent(new Student(first, last, gpa)); // Add 1st student
first = "Brenda";
last = "Stern";
gpa = 2.0;
course.addStudent(new Student(first, last, gpa)); // Add 2nd student
first = "Lynda";
last = "Robison";
gpa = 3.2;
course.addStudent(new Student(first, last, gpa)); // Add 3rd student
first = "Sonya";
last = "King";
gpa = 3.9;
course.addStudent(new Student(first, last, gpa)); // Add 4th student
beforeCount = course.countStudents(); // Number of students before dropping any students
last = "Stern";
course.dropStudent(last); // Should drop Brenda Stern
System.out.println("Course size: " beforeCount " students"); // Should output 4
System.out.println("Course size after drop: " course.countStudents() " students"); // Should output 3
}
}
uj5u.com熱心網友回復:
這段代碼有兩處錯誤:
if (nondrop.getLast() != last);
nonDropList.add(nondrop);
在 Java 中,if陳述句采用以下形式
if (CONDITION) SOME_CODE
如果條件CONDITION為true,則SOME_CODE執行,否則SOME_CODE跳過。
第一個問題是;在行尾if。這被解釋為SOME_CODEand 所以它是有條件地執行的。;在這樣的位置上的A本身就是一個空陳述句,執行它什么也不做。
解決此問題的一種方法是簡單地洗掉此分號。代碼中的下一個陳述句nonDropList.add(nondrop);, 將構成if陳述句的主體,因此只有在條件匹配時才會執行。SOME_CODE通常是條件之后的下一個陳述句,但是您可以if通過用大括號 ({和})將多個陳述句括起來將它們放入 an 中。即使您只有一個陳述句,我還是建議在此行周圍if加上大括號,以明確表示它適用于什么,并且如果您需要,也可以在將來更輕松地添加更多行。我還縮進了這一行,以表明它在if宣告的“內部” :
if (nondrop.getLast() != last) {
nonDropList.add(nondrop);
}
第二個問題是!=比較字串的使用。您需要使用.equals()來比較 Java 中的字串,原因是看到這個問題。沒有.notEquals()方法或類似方法,因此您必須使用.equals()并反轉結果:
if (!nondrop.getLast().equals(last)) {
nonDropList.add(nondrop);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351775.html
上一篇:沒有包裝節點的XML結構陣列?
