我正在使用Java中的這兩種方法驗證輸入。 searchCandidate方法搜索經過排序的數組以查找名稱與用戶輸入內容匹配的對象(String 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的名稱字段創建等於「零」,然後返回一個字符串通知沒有匹配候選用戶。如果它不等於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();
}
當我運行並放入一個不在數組中的對象的名稱時,不會返回任何內容。它只是循環回到我的用戶菜單。任何想法爲什麼發生這種情況?
用你正在使用的編程語言添加一個標籤是一個好主意 – alfasin
@alfasin滑動,添加它。謝謝。 – Paul
在輸入if之前,嘗試向控制檯輸出candidateChoice.getName()以確保將「null」更改爲其他值,以確保它指向的是字符串而不是狀態 –