0

i got array from user wanna hint in my assignment user input array elements and key and i'll check if the key found in the array or not and my output should be one line key found or not , and i tried more than time to fix it and thinking more but have no idea how to get only one output in same time i checking all array elements witch mean i'll get num of elements output lines ^_^

Scanner in=new Scanner(System.in);
        System.out.println("Enter array size ? ");
        int size=in.nextInt();
        int input[] = new int[size];

        for(int i=0;i<size;i++){
            System.out.println("Enter array element #"+i);
            input[i]=in.nextInt();
        }
        System.out.println("Enter key ? ");
        int key=in.nextInt();
        for(int i=0;i<size;i++){
            if(key!=input[i]){
                System.out.println("key not found");
            }else if(key==input[i]){
                System.out.println("key found");
            }
        }
VirusCD
  • 1
  • 1
  • 2
  • As well as the issue of string equality (see the duplicate) you're claiming that the key is not found *every* time you look at an array element which isn't right. You only want to do that after you've looked at *all* elements. – Jon Skeet Apr 03 '14 at 11:51

2 Answers2

0

Use status code for it

        Scanner in=new Scanner(System.in);
        int status=0;
        System.out.println("Enter array size ? ");
        int size=in.nextInt();
        int input[] = new int[size];

        for(int i=0;i<size;i++){
            System.out.println("Enter array element #"+i);
            input[i]=in.nextInt();
        }
        System.out.println("Enter key ? ");
        int key=in.nextInt();
        for(int i=0;i<size;i++){
            if(key==input[i]){
                status=1;
                break;
            }
        }
        if(status==1)
          System.out.println("key found");
        else
          System.out.println("key not found");
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30
0

Use the help of lists.

if (Arrays.asList(input).contains(key)) {
    System.out.println("key found");
} else {

    System.out.println("key not found");
}