Skip to content

Finding elements in array using for loop

import java.util.Arrays;
import java.util.Scanner;

public class Grocer2 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String[] names = new String[5];
        int count = 0;
        while(true){
            System.out.println("What is your name: ");
            // Store scanner input in name
            String name = scan.nextLine();
            // Add name into array
            names[count] = name;
            count++;
            if(count == 5){
                break;
            }
        }
        System.out.println(Arrays.toString(names));
        while(true){
            System.out.println("Who are you looking for ? ");
            String contact = scan.nextLine();
            for(int i = 0; i < names.length; i++){
                if(names[i].equals(contact)){
                    System.out.println("They are in aisle " + i);
                }else{
                    System.out.println("Not here");
                }
            }
            break;
        }
        scan.close();
    }
}

I am trying to add Scanner inputs into an array and I am trying to search for the element in an array using a for loop. The for loop looped through all the elements and print out “Not here” when names[i] is not equal to the Scanner input. How do I fix this issue ?

Answer

while(true){
    System.out.println("Who are you looking for ? ");
    String contact = scan.nextLine();
    bool isFound = false;
    for(int i = 0; i < names.length; i++){
        if(names[i].equals(contact)){
            System.out.println("They are in aisle " + i);
            isFound = true;
            break;
        }
    }
    if(!isFound){
        System.out.println("Not here");
    }
    break;
}