簡體   English   中英

為什么無法獲得具有指定條件的數組索引?

[英]Why can't I get the array index with the specified condition?

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循環內,即使String作者輸入與來自Details[i].getAuthor()的另一個String不同,也要輸入用於比較這兩個字符串的if語句,但我得到的索引是錯誤的。

為什么if語句不能正常工作? 有人可以告訴我我在做什么錯嗎? 非常感謝

看來您的問題在這里: if((Details[i].getAuthor()).equals(author));

由於在if語句后有不需要的分號,因此發生的情況是:

  1. 對該語句進行檢查和評估。
  2. ';' 標志着聲明的結束
  3. 始終執行以下代碼塊中的代碼。

嘗試刪除“;” 然后再試一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM