我正在使用 Java 中的这两种方法来验证输入。 searchCandidate 方法搜索排序数组以查找名称与用户输入(字符串 searchKey)匹配的对象。 displayCandidate 方法调用此方法,检查有效性,并返回该特定对象的所有值。
在 searchCandidate(正下方)方法中,如果找到匹配项,则返回该对象的副本。如果不存在,则返回一个所有字段都为“null”的新对象。
//Find user input candidate location in array
public static Candidate searchCandidate(Candidate[] candidate)
{
String currName;
int first = 0,
last = candidate.length-1,
middle;
Scanner kbd = new Scanner(System.in);
String searchKey = kbd.nextLine();
searchKey = searchKey.toUpperCase();
while(first <= last)
{
middle = (first + last)/2;
currName = candidate[middle].getName();
if(currName.equals(searchKey))
{
return new Candidate(candidate[middle]);
}
else if(currName.compareTo(searchKey)<0)
{
first=middle+1;
}
else
{
last = middle - 1;
}
}
return new Candidate("null","null","null","null");
}
在displayCandidate方法中,它检查searchCandidate创建的对象的name字段是否等于“null”,然后返回一个字符串,通知用户没有匹配的候选者。如果不等于 null,则返回所有对象值。
//Display candidates info after search
public static String displayCandidate(Candidate[] candidate)
{
System.out.println("Please enter the name of the candidate (LAST,FIRST)");
Candidate candidateChoice = searchCandidate(candidate);
if(candidateChoice.getName().equals("null"))
{
return "There are no candidates with this name.";
}
return candidateChoice.display();
}
当我运行并输入不在数组中的对象名称时,不会返回任何内容。它只是循环回到我的用户菜单。知道为什么会发生这种情况吗?
最佳答案
正如我们在评论中一起看到的,问题在于您根本没有使用方法的返回值来打印它。
当您输入正确的候选人姓名时它会打印一些内容,因为您使用了包含 print 方法的 display() 方法。
if(candidateChoice.getName().equals("null"))
{
return "There are no candidates with this name.";
}
return candidateChoice.display();
正确的解决方案是:
- 调整显示方法以在
Candidate
为 null 时显示某些内容
或者
- 创建一个新的
Candidate
方法,该方法仅返回一个字符串,而不显示包含有关 Candidate 的信息,并且对 null Candidates 有一个特殊的测试,您可以像这里一样使用
新代码:
public static String displayCandidate(Candidate[] candidate)
{
System.out.println("Please enter the name of the candidate (LAST,FIRST)");
Candidate candidateChoice = searchCandidate(candidate);
return candidateChoice.getInformation();
}
getInformation() 方法类似于:
public String getInformation(){
if (this.getName().equals("null"){
return "Candidate does not exist";
}else{
// Here belongs the information you want to display from the Candidate object
}
}
关于java - 使用用户输入搜索对象数组,验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684415/