Reputation: 2461
I am trying to write a method to search an array of names; with the ability to exit the search by entering an '*' either as the first char in the entered string or by itself... the logic seems to be be escaping me. im not sure what im doing wrong. the method should return the array element number if it is found, otherwise, -1.
public int searchNames(String [] names) throws IOException{
Scanner keyboard = new Scanner(System.in);
String line = "";
while (line.charAt(0) != '*'){
System.out.print("Enter a name to be searched, and an '*' to exit: ");
line = keyboard.nextLine();
for (int i = 0; i<name.length; i++){
if (names[i].compareTo(line) == 0){return i;}
}//end for loop
}//end while loop
return -1;
}//end searchNames
Upvotes: 0
Views: 90
Reputation: 280000
String line = "";
while (line.charAt(0) != '*'){
will throw a java.lang.StringIndexOutOfBoundsException
because there is no character at index 0
.
Use
String line = "";
while (!line.startsWith("*"))
Upvotes: 2
Reputation: 1975
You can also use
String line = "";
while(!line.startsWith("*"))
if you want strings starting with a "*" to cancel search.
Upvotes: 0