0
public class Book {
private String Author;
private Book[]Details;
public void setAuthor()
{
}
public String getAuthor()
{
return Author;
}
//Author already set for Array
public int getviewInfo()
{
System.out.println("Enter author");
Scanner kb= new Scanner(System.in);
int index=0;
String author= kb.next();
for(int i=0 ;i<Details.length; i++)
{
if((Details[i].getAuthor()).equals(author)); //compare both author
{
index=i;
//loop enters here even when author input not equal to getAuthor, why??
System.out.println("SAME author"); //& will continue to run this i times
}
}
System.out.println("sameindex "+index); //therefore index is wrong
return index;
}
我有一個方法getviewInfo()
它假設獲取數組對象的索引位置以供以後打印。它提示用戶輸入一個字符串「作者」,並將其與之前爲該數組設置的另一個字符串進行比較。爲什麼我無法獲得具有指定條件的數組索引?
問題是,在for循環中,比較這兩個字符串的if語句即使在字符串作者輸入不同於另一個來自Details[i].getAuthor()
的字符串時也會進入,我得到的索引是錯誤的。
爲什麼if語句不能正常工作?有人能告訴我我做錯了什麼嗎?感謝這麼多
也索引初始值= 0,所以即使沒有匹配,方法將返回0。你應該返回-1如果匹配沒有找到 –
謝謝,@ MaximTulupov絕對正確。 – Omrisk
非常感謝,犯了一個愚蠢的語法錯誤,刪除分號解決了問題。 – Jackaliar