I have to search a string in an array from the user input, but I have an error in my logic. Even when the user input is in the array I still get "data not found"
I also have to display the index where the string is located in the array if it's found but got an error there too.
Below is the code I've tried.
This was the original question
- create a program that ask user to insert 5 names.
- store names in array
- ask user to insert the name they want to find from the list created earlier
- if name found, display "data found at [index]"
- if not, display "data not found". Hint; use Java method equals to compare two strings.
package stringsearch;
import java.util.Scanner;
public class StringSearch
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
String [] names = new String[5];
for (i = 0; i < names.length; i++)
{
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
if (names.equals(inName)){
System.out.println("Data found at ["+i+"]");
}
else
{
System.out.println("Data not found!");
}
}
}