Та же проблема, что и this post, но я думаю, что я приближаюсь к ее решению.Код не уронит студентов с курса [Java]
В моем коде, в двух словах, есть два курса, и я должен отбросить несколько учеников от каждого из них, а затем полностью очистить второй курс. Этот код выполняется с использованием двух классов.
Это то, что я до сих пор:
/*
Program description:
Starting with listing 10.5 and 10.6 below, you are to modify the two source
files to:
Course.java:
add method increaseArray().
Increase the array when students are added by 1, (hint utilize
System.arraycopy method). Then add the student to the last location. I
would suggest you set the size of the “students” array to a size initially
of zero, so when the any student is added, your code to increase the
array will be triggered.
add method dropStudent().
Drop student would need to find the String match by iterating on the
students array using the .equals String method. When a match is found,
remove that entry by assigning the next student into the match location,
and do for all the remaining students (effectively shift remaining
students by one). Also you would have also decrement the
numberOfStudents count.
add method clear().
Iterating on the students array assign all to null and set the
numberOfStudents count to 0.
TestCourse.java:
You need to test your new methods; this is done by modifying listing 10.5 to
meet the requirements of assignment which are:
Create a two courses
Add six students to the first, three students to the second
Remove the first two student from course one
Remove the second student from course two
Display students in both classes
Clear the second course
Display students in both classes
Add a static method to TestCourse that handles printing the students in a
class. This method receives the reference of the course and the course
number. This way, you just call the method to print out the students.
*/
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
int IndexOfStudentToDrop = -1;
for (int i = 0; i < numberOfStudents; i++) {
if (students[i].equalsIgnoreCase(student)) {
IndexOfStudentToDrop = i;
if (IndexOfStudentToDrop != -1) {
for (i = IndexOfStudentToDrop; i < numberOfStudents; i++)
students[i] = students[i+1];
} // end if found
// decrement number of students by 1
numberOfStudents--;
}
}
}
public void clear() {
for (int i = 0; i < numberOfStudents; i ++){
students [i] = null;
}
numberOfStudents = 0;
}
public void increaseArray() {
if (numberOfStudents >= students.length) {
String[] temp = new String[students.length * 2];
System.arraycopy(students, 0, temp, 0, students.length);
students = temp;
}
} // end of increaseArray()
public String toString()
{
String output = "";
output += getCourseName()+ (getNumberOfStudents() + "students");
for (int i = 0; i < getNumberOfStudents(); i++) {
output += "\n("+ (i + 1)+")"+ students [i];
}
return output;
}
}
и
public class TestCourse {
public static void main(String[] args) {
// create two courses
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
// introduce the program
System.out.println("Creating Two Courses");
System.out.println("Adding 6 students to course 1");
System.out.println("Adding 3 students to course 2");
// add six students to course1
course1.addStudent("\n1: Tom Servo");
course1.addStudent("\n2: Joel Robinson");
course1.addStudent("\n3: Mike Nelson");
course1.addStudent("\n4: Pearl Forrester");
course1.addStudent("\n5: TV's Frank");
course1.addStudent("\n6: Zap Rowsdower");
System.out.println();
System.out.println();
// add three students to course2
course2.addStudent("\n1: Tom Servo");
course2.addStudent("\n2: Crow T. Robot");
course2.addStudent("\n3: Zap Rowsdower");
System.out.println();
System.out.println();
// output to the console
System.out.println ("Number of students in Course 1: " + course1.getNumberOfStudents() + " Students are: ");
String [] students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students[i]);
System.out.println();
System.out.print("Number of students in Course 2: " + course2.getNumberOfStudents() + " Students are: ");
String [] students1 = course2.getStudents();
for (int i = 0; i < course2.getNumberOfStudents(); i++)
System.out.print(students1[i]);
// output to the console how many students will be dropped from each class
System.out.println("dropping 2 students from course 1");
System.out.println("dropping 1 student from course 2");
// drop some students.
course1.dropStudent("Tom Servo");
course1.dropStudent("Joel Robinson");
System.out.println ("\nNumber of students in Course 1: " + course1.getNumberOfStudents() + " Students are: ");
course2.dropStudent("Crow T. Robot");
System.out.println("\nNumber of students in Course 2: " + course2.getNumberOfStudents() + " Students are: ");
// clear course2, but keep course1 as it currently stands
System.out.println("\nclearing course 2 course 2");
course2.clear();
System.out.println("\nNumber of students in Course 1: " + course1.getNumberOfStudents() + " Students are: ");
System.out.println("\nNumber of students in Course 2: " + course2.getNumberOfStudents() + " Students are: ");
}
}
Это то, что вывод должен выглядеть следующим образом:
Creating Two Courses
Adding 6 students to course 1
Adding 3 students to course 2
Number of students in Course 1: 6 Students are:
1: Tom Servo
2: Joel Robinson
3: Mike Nelson
4: Pearl Forrester
5: TV's Frank
6: Zap Rowsdower
Number of students in Course 2: 3 Students are:
1: Tom Servo
2: Crow T. Robot
3: Zap Rowsdower
dropping 2 students from course 1
dropping 1 student from course 2
Number of students in Course 1: 4 Students are:
1: Mike Nelson
2: Pearl Forrester
3: TV's Frank
4: Zap Rowsdower
Number of students in Course 2: 2 Students are:
1: Tom Servo
2: Zap Rowsdower
clearing course 2 course 2
Number of students in Course 1: 4 Students are:
1: Mike Nelson
2: Pearl Forrester
3: TV's Frank
4: Zap Rowsdower
Number of students in Course 2: 0 Students are:
Но это то, что происходит вместо этого:
Creating Two Courses
Adding 6 students to course 1
Adding 3 students to course 2
Number of students in Course 1: 6 Students are:
1: Tom Servo
2: Joel Robinson
3: Mike Nelson
4: Pearl Forrester
5: TV's Frank
6: Zap Rowsdower
Number of students in Course 2: 3 Students are:
1: Tom Servo
2: Crow T. Robot
3: Zap Rowsdowerdropping 2 students from course 1
dropping 1 student from course 2
Number of students in Course 1: 6 Students are:
Number of students in Course 2: 3 Students are:
clearing course 2 course 2
Number of students in Course 1: 6 Students are:
Number of students in Course 2: 0 Students are:
Как вы можете видеть, мой код не отбрасывает студентов, когда мне это нужно (хотя очистка не кажется проблемой). Я знаю, что мое форматирование испорчено, но это не моя главная проблема, и я мог бы это исправить самостоятельно. Помимо форматирования, меня бросают ученики - моя единственная проблема, и если бы я мог просто помочь с этим, я могу взять это отсюда.
Где находится ваш класс 'Student'? Особенно интересует метод сравнения студентов ('equalsIgnoreCase') – Vucko
Студент - это имя строки, которая используется для удаления учащихся из определенного класса. –