所以如果我理解正确的话,你想要做的是关于以下内容:
if (containsName(studentNamesArray, studentName) == false) {
addStudent(studentNamesArray, studentName);
}
此外,这可以使用 Java Set 轻松解决,如下所示:
studentSet.add(studentName); // automatically ignores duplicates
您需要为第一个代码部分做的就是编写函数containsName 和addStudent
boolean containsName(String[] studentNamesArray, String studentName) {
for (int i = 0; i < studentNamesArray.length; ++i) { // specialized while loop over all array elements
if (studentName.equals(studentNamesArray[i])) { // use equals for String comparison! This will as well not match on "null"
return true; // we found a match
}
}
return false; // no match was found
}
和
void addStudent(String[] studentNamesArray, String studentName) {
int i = 0;
while ((studentNamesArray[i] != null) && // this student entry is already filled by someone else
(i < studentNamesArray.length)) { // we are still within the array bounds
++i;
}
if (i < studentNamesArray.length) { // is i still within the array bounds?
studentNamesArray[i] = studentName; // add the student
} else {
// we have too many students. What to do now?
}
}
这段代码有几处没有检查:
- 如果学生人数超过数组大小怎么办?
- 如果 studentName 是
null 怎么办?
这种编写代码的方法称为Top-down approach,如果您了解一般程序逻辑但还不了解详细信息,则可以更轻松地编写代码。
编辑:完整代码:
import java.util.Scanner;
public class Test {
static boolean containsName(String[] studentNamesArray, String studentName) {
for (int i = 0; i < studentNamesArray.length; ++i) { // specialized while loop over all array elements
if (studentName.equals(studentNamesArray[i])) { // use equals for String comparison! This will as well not match on "null"
return true; // we found a match
}
}
return false; // no match was found
}
static void addStudent(String[] studentNamesArray, String studentName) {
int i = 0;
while ((studentNamesArray[i] != null) && // this student entry is already filled by someone else
(i < studentNamesArray.length)) { // we are still within the array bounds
++i;
}
if (i < studentNamesArray.length) { // is i still within the array bounds?
studentNamesArray[i] = studentName; // add the student
} else {
// we have too many students. What to do now?
}
}
public static void main(String[] args) {
final String[] studentNamesArray = new String[10];
String studentName;
final Scanner scanner = new Scanner(System.in);
do {
System.out.println("Please insert your name:");
studentName = scanner.nextLine();
if (studentName.length() > 0) {
if (containsName(studentNamesArray, studentName) == false) {
addStudent(studentNamesArray, studentName);
System.out.println(studentName + " added.");
} else {
System.out.println(studentName + " was already in the list.");
}
}
} while (studentName.length() > 0);
for (int i = 0; i < studentNamesArray.length; ++i) {
System.out.println("Student #" + i + ": " + studentNamesArray[i]);
}
}
}
使用示例输入,我得到以下信息:
请填写您的姓名:
二
加了两个。
请填写您的姓名:
测试
添加了测试。
请填写您的姓名:
测试
测试已经在列表中。
请填写您的姓名:
测试
添加了测试。
请填写您的姓名:
测试
test 已经在列表中。
请填写您的姓名:
学生 #0:两个
学生 #1:测试
学生#2:测试
学生 #3:空
学生 #4:空
学生 #5:空
学生 #6:空
学生 #7:空
学生 #8:空
学生 #9:空