0

When i replace EmpNo(Integer) to EmpName(String) its working properly. My code is not working for Int. If i search a string in my Array its working but when i search Integer in my array, the ouput is Employee Number not Found!!

int EmpNo[]=new int[a];

switch(a){
    case 1:
        System.out.print("Enter Employee Number:");
        number = Integer.parseInt(reader.readLine());
        int y = Arrays.asList(EmpNo).indexOf(number);
        if(Arrays.asList(EmpNo).contains(number))
        {
            System.out.print("Employee Number: "+EmpNo[y]+" \nEmployee Name "+EmpName[y]+" \nSalary "+Salary[y]+"");
        }
        else
        {
            System.out.println("Employee Number not Found!!");
        }
        break;
}
laune
  • 31,114
  • 3
  • 29
  • 42

4 Answers4

0

Change

int EmpNo[]=new int[a];

to

Integer EmpNo[]=new Integer[a];

Also there is not need to use contains() when indexOf() is already used before. Value of y can tell you if number is present in EmpNo or not. if y == -1, employee not found else found at location y.

dips
  • 76
  • 4
0

As David Wallace has pointed out the int[] does not autobox to Integer[] but will be automatically converted to a singular Object.

Define empNo as

Integer [] empNo = new Integer [a] (); 

Also if indexOf is -1 then contains will also be false.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

EmpNo is an array of primitive integers. A List<> cannot store primitive data types. It needs Integers instead. So when you do:

Arrays.asList(EmpNo)

it returns a List<int[]> instead of a List<Integer>. So the contains and indexOf obviously do not match for an int.

If you can change the type of EmpNo, the simplest solution is to declare it as:

Integer[] EmpNo = new Integer[a];

Notice the Integer instead of the int. This should work correctly. If you cannot change the type of EmpNo, you will need to use some other methods as given here:

Arrays.asList() not working as it should?

Community
  • 1
  • 1
metacubed
  • 7,031
  • 6
  • 36
  • 65
-2

.contains() will treat the argument inside it as string.so,try using something like

if(Arrays.asList(EmpNo).contains(new Int (number))