【问题标题】:Why can't I get the array index with the specified condition?为什么获取不到指定条件的数组索引?
【发布时间】:2017-04-05 05:32:35
【问题描述】:
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 循环中,即使字符串作者输入的字符串与来自Details[i].getAuthor() 的另一个字符串不同,也会输入比较这两个字符串的 if 语句,我得到的索引是错误的。

为什么 if 语句不能正常工作?有人可以告诉我我做错了什么吗?非常感谢

【问题讨论】:

    标签: java arrays search


    【解决方案1】:

    您的问题似乎在这里: if((Details[i].getAuthor()).equals(author));

    由于 if 语句后面有一个不需要的分号,所以发生的情况是:

    1. 对语句进行检查和评估。
    2. ';'标记语句的结束
    3. 始终执行以下代码块中的代码。

    尝试删除';'然后再试一次。

    【讨论】:

    • 同样索引初始值 = 0,所以即使没有匹配,方法也会返回 0。如果未找到匹配项,则应返回 -1
    • 非常感谢,犯了一个愚蠢的语法错误,删除分号解决了问题。
    • 抱歉@Omrisk,可以就另一个问题寻求您的帮助吗?
    • 这是关于向我创建的数组添加一个新对象,如何在不使用任何 Java 库类来存储数组的情况下做到这一点?
    • 好吧,如果您想要一个可以“动态”添加对象的数组,那么您可能应该考虑使用某种列表。 You can see an example of a similar question here
    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 2020-09-11
    • 2011-12-30
    • 2017-08-30
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多