Hi MorneDV,
I had the same run-time error. It's very simple, look over your while
loop, if there is no actual match then "i" will keep incrementing,
which exceeds names.length, thus returning the
ArrayIndexOutOfBoundsException. i++ needs to be placed after the if
block within the while loop:
int i = 0
while (i<names.length){
if (names [i].equals(searchName)){
foundName = true;
break;
}
i++;
}
This will now work beautifully, let me know if results show otherwise.
Ml, Lou
On Nov 26, 7:41 pm, 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