This is going to be closed soon, but use .equals()
to compare Strings.
Sequential String search in Java [duplicate]
-
03-04-2022 - |
Pregunta
Hello again stack overflow.. ers, I have created this bit of code to sequentially search through an array to find a value, in this case a name. However i cant get it to work, it wont find the name i type in, and always returns a value of -1.
When i changed all of the types to INT and did a search on the age array, it worked, so it may have something to do with the string type? Can someone please help me?
public static void main(String[] args) {
String[] name = {"John", "bert", "Elle", "beth"};
String[] sex = {"Male", "Male", "female", "female"};
int[] age = {18, 25, 22, 36};
int found;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name to search: ");
String searchName = keyboard.next();
found = searchNames(name, searchName);
if(found == -1)
System.out.println("Error, not found: " + found);
else
System.out.println("Found At: " + found);
}
private static int searchNames(String[] name, String searchName) {
int i = 0, foundAt = -1;
boolean found = false;
while (!found && i < name.length)
{
if (name[i] == searchName)
{
found = true;
foundAt = i;
}
i++;
}
return foundAt;
}
Solución
Otros consejos
Try replacing this portion of your code
while (!found && i < name.length)
{
if (name[i] == searchName)
{
found = true;
foundAt = i;
}
i++;
}
with
for(int i=0; i<name.length; i++)
{
if(name[i].equalsIgnoreCase(searchName))
{
found = true;
foundAt = i;
break;
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow