Home > Enterprise >  For loop with if, else not working as it is printing the else if section even though element is in t
For loop with if, else not working as it is printing the else if section even though element is in t

Time:04-10

I know that the loop is looping through every element in the array! Hence, it also prints out 'John is not found' before printing out his information! How do I just print out his information without 'John is not found'?

This is my code:

public static void main(String[] args) {
    
    Scanner scanner = new Scanner(System.in);
    
    System.out.print("Number of members: ");       
    int number = scanner.nextInt();
    Member m[] = new Member[number];
    scanner.nextLine();
    
    for (int i = 0; i < number; i  ) {
        System.out.print("Name & number:");
        String[] input = scanner.nextLine().split(" ", 2);
        m[i] = new Member(input[0], input[1]);
    }  
    
    System.out.println("Information Saved.\n");
    
    boolean condition = true;
    while (condition) {
        System.out.print("Search a name or type exit: ");
        String search = scanner.nextLine();
            
        for (int x = 0; x < m.length; x  ) {
            if (search.equals(m[x].getName())) {
                System.out.print(search   "'s number is "   m[x].getTel()   "\n");
                break;
            } else if (search.equals("exit")) {
                condition = false;
                m[x].showAllMembers();
            } else if (!search.equals(m[x].getName())){
                System.out.print(search   "is not found.\n");
            }
        }
    }
}

Member class:

class Member {
    private String name, tel;
    
    public Member(String name, String tel ) { // Constructor
        this.name = name;
        this.tel = tel;
    }
    
    // Getter
    public String getName() {
        return name;
    }
      
    // Setter
    public void setName(String name) {
        this.name = name;
    }
    
    // Getter
    public String getTel() {
        return tel;
    }
          
    // Setter
    public void setTel(String tel) {
        this.tel = tel;
    }
    
    public void showAllMembers() {
        System.out.print("Name:"   name   ", Number:"   tel   "\n");
    }

Results:
After running it

CodePudding user response:

I assume you can do the following:

public static void main(String[] args) {
    
    Scanner scanner = new Scanner(System.in);
    
    System.out.print("Number of members: ");       
    int number = scanner.nextInt();
    Member m[] = new Member[number];
    scanner.nextLine();
    
    for (int i = 0; i < number; i  ) {
        System.out.print("Name & number:");
        String[] input = scanner.nextLine().split(" ", 2);
        m[i] = new Member(input[0], input[1]);
    }  
    
    System.out.println("Information Saved.\n");
    
    boolean condition = true;
    while (condition) {
        System.out.print("Search a name or type exit: ");
        String search = scanner.nextLine();
        
        if (search.equals("exit")) {
            condition = false;
            // method showAllMembers() should not exists in Member class, it'll be really better to migrate it to the separate method, because one single Member object shouldn't know anything about ALL members
            showAllMembers(m);
        }
        int memberNumber = -1;
        for (int x = 0; x < m.length; x  ) {
            if (search.equals(m[x].getName())) {
                memberNumber = x;
                break;
            }
        }
        if (memberNumber != -1) {
            System.out.print(search   "'s number is "   m[memberNumber].getTel()   "\n");
        } else {
            System.out.print(search   "is not found.\n");
        }
    }
    
    public static void showAllMembers(Member members[]) {
        for (Member member : members) {
            System.out.println("Member name: "   member.getName()   ", number: "   member.getTel());
        }
    }
}

CodePudding user response:

You can fix it by taking the not found condition out of the for loop. Which will print the details if the name has been found, or print not found after the for loop finish to iterate and "found" variable is still false.

public static void main(String[] args) {
    
Scanner scanner = new Scanner(System.in);

System.out.print("Number of members: ");       
int number = scanner.nextInt();
Member m[] = new Member[number];
scanner.nextLine();

for (int i = 0; i < number; i  ) {
    System.out.print("Name & number:");
    String[] input = scanner.nextLine().split(" ", 2);
    m[i] = new Member(input[0], input[1]);
}  

System.out.println("Information Saved.\n");

boolean condition = true;
while (condition) {
    System.out.print("Search a name or type exit: ");
    String search = scanner.nextLine();
    boolean found = false;
    for (int x = 0; x < m.length; x  ) {
        if (search.equals(m[x].getName())) {
            System.out.print(search   "'s number is "   m[x].getTel()   "\n");
            found = true;
            break;
        } else if (search.equals("exit")) {
            condition = false;
            m[x].showAllMembers();
    }
    if (!found) {
      System.out.print(search   "is not found.\n");
    }
}

}

CodePudding user response:

The code is printing the "not found" message too often at the moment because it's printing it every time it finds a member which isn't a match. You only want to print it when you've reached the end of the for loop.

Personally I'd extract the code into a method, which means you can just return when you've found the member. I'd also move the "check for exit" code outside the for loop.

So your while loop would look like this:

// No need for a "condition" variable - just break when we've seen "exit"
while (true) {
    System.out.print("Search a name or type exit: ");
    String search = scanner.nextLine();
    if (search.equals("exit")) {
        break;
    }
    findMember(m, search);
}

And the findMember method would look like this:

// TODO: You might want to return the member you've found
private static void findMember(Member[] members, String name) {
    for (Member member : members) {
        if (name.equals(member.getName()) {
            // TODO: use string formatting here
            System.out.println(name   "'s number is "   member.getTel());
            return;
        }
    }
    System.out.println(name   " is not found.");
}
  • Related