以下Java方法假設通過鍵盤接受用戶的字符串(人的姓名),在名爲name[]
的數組中搜索該名稱並從數組中刪除該人的姓名(由分配name[i] = "INVALID"
)。使用掃描儀讀取輸入時的NoSuchElementException
代碼試圖接受使用Scanner
類對象del_name
輸入字符串(人的名字),但我在聲明中
s=del_name.next();
即從頂部的第4語句得到一個NoSuchElementException
。
如果有人可以提供解決方案並解釋爲什麼此代碼不起作用,我將非常感激。 (謝謝)
void Deletee()
{
Scanner del_name=new Scanner(System.in);
String s;
System.out.println("Enter the name to be deleted");
s=del_name.next(); // causing NoSuchElementException
int i=0;
/* find position in which the name occurs using while-loop below */
while(!s.equalsIgnoreCase(name[i]) && i<count)
i++ ; // increment i to search in next array index
if(i<count)
{
name[i]="INVALID";
count--;
System.out.println("Deletion Successful");
}
else
{
System.out.println("No such person exist");
}
del_name.close();
}