Checked the Entered Array and Dispaly the error and that was in loop

Viewed 42

I have a List of Array values

String[] names = {"michel","john","mr x","text"};
 int[] num ={1,2,3,4};

I asked the User to Enter the names in the array and want to dispaly the num of tht array names also we want to check whether the entered array is in the array if not then we want to send error msg

for that i created a boolean = false and check the condition in loop and i execute

System.out.println("Enter the Name To get Numbers");
Scanner scanner = new Scanner(System.in);
String name=scanner.next();
boolean check =false;
int in = 0;
for (int i=0; i <names.length; i++)
{
    if (name.contains(names[i]))
    {
        check = true;
        in = i;
    }
    if (name.equals(names[i]))
    {
        System.out.println(num[i]);
      

    }else
    {
        System.out.println(" Choose the name in the array ");
    }
 }

But it execute the error in the loop till the no of array list

2 Answers

First search in the array with for loop exists or not in the array if exist then do check = true and print the number.

And after the loop check is not in the array then print the error message.

Scanner scanner = new Scanner(System.in);
String name=scanner.next();
boolean check =false;
for (int i=0; i <names.length; i++)
{
    if (name.equals(names[i]))
    {
        check = true; // if match with any array element
        System.out.println(num[i]);
    }
}
// if check is false means no element match in array, print err msg
if(!check)
{
   System.out.println(" Choose the name in the array ");
}

You set the values for check and in variables, but you never use them. You also print "Choose the name in the array" inside the loop for every non-matching value, but you probably only want to do this once, when the loop is finished, in case you didn't find anything.

This is how you could rewrite your loop to get what you want:

boolean check = false;
for (int i = 0; i < names.length; i++) {
    if (name.equals(names[i])) {
        check = true;
        System.out.println(num[i]);
    }
}
if (!check) {
    System.out.println(" Choose the name in the array ");
}

Actually, if you want to look up values by names, a HashMap would probably be a better choice than iterating through an array:

Map<String, Integer> map = new HashMap<>();
map.put("michel", 1);
map.put("john", 2);
map.put("mr x", 3);
map.put("text", 4);

Integer in = map.get(name);
if (in == null) {
    System.out.println(" Choose the name in the array ");
}
else {
    System.out.println(in);
}
Related