Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading