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;
}

I have a method getviewInfo() which suppose to get index position of the array object for printing later. It prompt user to enter a String 'author', take it and compare for equality with another String which has been set earlier for the Array.

Problem is, inside the for loop, the if statement to compare these 2 strings will enter even when String author input is different than the other String from Details[i].getAuthor(), an the index i gotten is wrong.

Why isn't the if statement working correctly? can someone tell me what am I doing wrong? Thank so much

SAMUEL
  • 8,098
  • 3
  • 42
  • 42
Jackaliar
  • 3
  • 2

1 Answers1

5

Looks like your problem is here: if((Details[i].getAuthor()).equals(author));

Since you have an unneeded semicolon after the if statement what happens is:

  1. The statement is checked and evaluated.
  2. The ';' marks the end of the statement
  3. The code in the following code block is always executed.

Try removing the ';' and try again.

Omrisk
  • 151
  • 9
  • Also index initial value = 0, so method will return 0 even there is no match. You should return -1 if match not found – Maxim Tulupov Apr 05 '17 at 07:22
  • Many thanks, made a foolish syntax mistake, removing the semicolon fix the problem. – Jackaliar Apr 05 '17 at 07:45
  • Sorry @Omrisk, is it okay to ask for your help for another question? – Jackaliar Apr 06 '17 at 14:11
  • It's about adding a new object to the array that I have created, How can I do this without using any Java library class to store the Array? – Jackaliar Apr 06 '17 at 14:15
  • Well if you want to have an array where you can add objects "on the fly" then you should probably think about using a list of some sort. [You can see an example of a similar question here](http://stackoverflow.com/questions/10400373/add-an-object-to-an-array-of-a-custom-class) – Omrisk Apr 08 '17 at 10:43