How do you search for a word in a String array in Java?(10 point Question for any Java wiz)?
-
Is my sequentialSearch method set up correctly? I'm having trouble figuring out how to search for a String, compare the String in the method etc. But I think the problem might be in the main. p.s I would also like the program to find the index of the string array when phrase found. it seems like n is returning nothing in main. right now it has a runtime error. Here is my code.... import java.util.Scanner; public class Internet { public static void main(String[] args) { String[] names = new String [4]; names[1] = "kook"; names[2] = "cook"; names[3] = "goop"; names[3] = "soup"; Scanner keyboard = new Scanner(System.in); String newName; int results; System.out.print("\nPlease enter in a name: "); newName = keyboard.nextLine(); results = sequentialSearch(names, newName); if (results != -1) { System.out.print("\nFound the name " + newName ); } else { System.out.print("\nCannot find name " + newName); } } public static int sequentialSearch(String[] names, String name) { for (int n = 0; n < names.length; n++) { if (names[n].equals(name)) return n; } return -1; } }
-
Answer:
names[3] = "goop"; names[3] = "soup"; That can't be good. Array's are zero indexed. names[0] = ""; . . names[3] = "";
David M at Yahoo! Answers Visit the source
Related Q & A:
- How can I echo characters before and after a string?Best solution by stackoverflow.com
- How do you search for a yahoo user?Best solution by Yahoo! Answers
- How do I search for a Bengali magazine?Best solution by infibeam.com
- How can I search for a person's personal cell phone number?Best solution by Yahoo! Answers
- How do I search for a Yahoo member's profile?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.