Mostafizur Rahman Mostafizur Rahman - 1 month ago 5
Java Question

How to return to index number

I am trying to write a program where the user can write their grocery item list, and then they can search whether they have wrote that item on the list or not. When they find if they have wrote down the item name it's suppose to return the index number and if they haven't wrote down the item name it's suppose to return -1. So far my code is able to find out if they have wrote down the item or not in Boolean expression.

import java.util.Scanner;
import java.util.Arrays;

public class GroceryStoreTest {
// for the search item we need to create a method.

I wrote down a boolean method for the search item.

public static boolean contains(String [] arr, String targetItem){
for(String find : arr){
if(targetItem.equals(find))
return true;

} return false ;
}

public static void main(String[] args) {

//lets create an array of string and add items list

int list;
Scanner input = new Scanner(System.in);
System.out.print("How many items would you like to add to the list: ");
list = input.nextInt();

String[] items = new String[list];

System.out.print("Write down the name of item without any space.\n(i.e.; Green Paper = GreenPaper)\n\nItems list: \n");


int i;
for (i = 0; i < list; i++) {
System.out.printf((i+1 ) + ".");
items[i] = input.next();// asks for next item name

}

// search in the items list

String search = " ";
System.out.print("Enter the name of the item to check if you have listed: " + search);
search = input.next();
//System.out.print(contains(items, String.valueOf(input)));
System.out.print(contains(items, search));
input.close();// it will stop taking the input
}
}

Answer

Why not just change your contains method to return an int instead?

public static int indexOf(String [] arr, String targetItem){
    for(int i = 0 ; i < arr.length ; i++) {
        if(targetItem.equals(arr[i]))
            return i;

    }
    return -1 ;
}

Alternatively, you don't need to create your own indexOf method, you can just call Arrays.asList(items).indexOf("valueSearch") to get the index.

Another way to do this is to use an array list instead of an array. An ArrayList is basically an array without a fixed length. Your code will look like this:

Scanner input = new Scanner(System.in);

ArrayList<String> items = new ArrayList<>();

System.out.print("Write down the name of item without any space.\n(i.e.; Green Paper = GreenPaper)\n\nWrite "END" to finish entering items\n\nItems list: \n");


while(true) {
    String item = input.next();
    if (item.equals("END")) {
        break;
    }
    items.add(item);
}

// search in the items list

String search = " ";
System.out.print("Enter the name of the item to check if you have listed: " + search);
search = input.next();
System.out.print(items.indexOf(search));
input.close();// it will stop taking the input