If I comment your code you might be able to see more clearly why there
is an error:

       // initialize counter i equal to zero
       int i = 0;

       // keep repeating this loop if the counter is not equal to the
number of names
       while (i<names.length)
       {
              // add one to the counter, so now i = {1, ...,
names.length}
              i++;
              [do something with the counter]
       }


Well, the counter ranges from 1 to names.length+1, since one is added
to the counter before you check anything with the counter. The big
problem is that the maximum array index is names.length, but on the
last loop, the array index is i = names.length, which is too big! You
can fix it just like miga suggested.

Tommy


On Jun 28, 4:45 am, Dan <[email protected]> wrote:
> When I run my program, it is ok with 'Yza'. When I run with 'noname' ,
> receive this message
> "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
>         at OwnWhileProject.main(OwnWhileProject.java:27)"
>
> I think this has to do with where I placed my i++. My code is below.
> Thanks for the help, I have been attempting to fix this for 4 days now!!
>
> import javax.swing.JOptionPane;
>
> public class OwnWhileProject {
>
>     /** Creates a new instance of WhileLoop */
>     public OwnWhileProject() {
>     }
>
>     /**
>      * @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 called
> 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
-~----------~----~----~----~------~----~------~--~---

Reply via email to