Hello guyz Just written a small code trying to make a scenario in which I get a name from user and see that the provided name is present in my array list if it is then it displays name found if not present in array it simply says name not found i haev tried it alot time but not suceeded can anyone help me out where i am doing mistake?

import java.util.Scanner;
public class Mypractice {

    public static void main(String[] args) {

        newthis obg = new newthis(24, 6);

        Scanner obj2 = new Scanner(System.in);
        String name;

        String[] arr = new String[4];

        arr[0] = "Usman"  ;
        arr[1] = "Talha"  ;
        arr[2] = "Mairaj" ;
        arr[3] = "Kokab"  ; 

        System.out.print("Enter a name to search :" );
        name = obj2.nextLine();

        int count = 0;
        int wrong = 0;

        for(int i=0; i<=4; i++)
        {
            if(name.equals(arr[i]))
            {
                System.out.println("Name found");
            }
            else 
            {
                System.out.println("Name not found");
                break;
            }
        }


    }

}

Recommended Answers

All 4 Replies

Look at line 33.
As soon as you test a name that's not in the very first element of the array you break from the loop and stop looking.
You probably intended to break after finding a match.

yes because when i remove break i founds the very first name once the first name in the arrays is found it loops else block 4 time so in order to stop that i placed break; keyword and gives me this output

Enter a name to search :Talha
Name not found
Name found
Name not found
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at mypractice.Mypractice.main(Mypractice.java:27)
Name not found
Java Result: 1

in order to avoid the ArrayIndexOutOfBoundsException,
replace this:
for(int i=0; i<=4; i++)
by
for(int i=0; i<4; i++)

but, your logic is wrong: you should only print whether the name is found after all checks have run: try this:

- set a flag 'found' to false
for(int i=0; i<4; i++)
        {
            if(name.equals(arr[i]))
            {
                - set flag 'found' to true
                break;
            }
        }

        - if flag 'found' ->
         System.out.println("The name was found");

        - if flag 'found' false ->
         System.out.println("The name was not found");

I just mingled your code a bit up with some pseudocode, but it should give you enough to get it to work.

so in order to stop that i placed break; keyword

yes, but did you see my comment "You probably intended to break after finding a match."? YOur break is after NOT finding a match!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.