In your while loop you need put the i++; statement after your if statement, otherwise on your last time through the while loop it will increment you to an array index that does not exist.
Richard On 11/26/09, MorneDV <[email protected]> wrote: > Can someone help please? > > I just started the J2SE online training cource. > I have a problem with the homework part in the control structure > section.The homework is to modify the MyForLoopProject project and use > the while loop. > The code works correctly if you type a valid name listed in the array. > When you type an name not listed in the array I get an error...instead > of displaying ("noname" is not found) > Error: > Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: > 8 > at MyOwnWhile.main(MyOwnWhile.java:26) > Java Result: 1 > BUILD SUCCESSFUL (total time: 6 seconds) > > Code: > import javax.swing.JOptionPane; > > public class MyOwnWhile { > > /** Creates a new instance of MyOwnWhile */ > public MyOwnWhile() { > } > > /** > * @param args the command line arguments > */ > public static void main(String[] args) { > // Declare and initialize String array variable called names. > String names []= > {"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"}; > > // This is the search string we are going to use to search the > array. > String searchName = JOptionPane.showInputDialog("Enter either > \"Yza\" or \"noname\"!"); > > // Declare and initialize boolean primitive type variable > calld foundName. > boolean foundName =false; > > int i=0; > while (i<names.length){ > i++; > > if (names [i ].equals(searchName)){ > foundName =true; > break; > } > } > > // Display the result > if (foundName) > JOptionPane.showMessageDialog(null, searchName + " is > found!"); > > else > JOptionPane.showMessageDialog(null, searchName + " is not > found!"); > > } > > } > > -- > To post to this group, send email to > [email protected] > To unsubscribe from this group, send email to > [email protected] > For more options, visit this group at > http://groups.google.com/group/javaprogrammingwithpassion?hl=en -- Sent from my mobile device -- To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/javaprogrammingwithpassion?hl=en
