while loop problem

R

roohbir

Hello all,
I have this code where I am required to use a while loop instead of a
for loop to achieve the same result ( it asks the user to enter Yza or
noname; if Yza is entered it looks for that in the array and displays
that the name was found). I am having problems with the while loop .
The initial for loop code is commented out. Can anyone please point
out the error?
Thanks a lot.
ros

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
import javax.swing.JOptionPane;

public class ForLoop {

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 counter = 0;
while ( counter < 7 ){
if (names [counter].equals(searchName)){
counter++;
foundName = true;
break;
}
}



/*for (int i=0; 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!");

}

}
 
F

Flo 'Irian' Schaetz

And thus spoke roohbir...
int counter = 0;

Ok, you start at 0...
while ( counter < 7 ){

as long as you are not > 6...
if (names [counter].equals(searchName)){
counter++;
foundName = true;
break;
}

Ok, IF you find a name, you increase the counter... But what happens if
you don't find one? In the next round, you will check the SAME name
again - and again - and again...

You must increase your counter, no matter if you found a name or not :)

Flo
 
D

Daniel Pitts

And thus spoke roohbir...
int counter = 0;

Ok, you start at 0...
while ( counter < 7 ){

as long as you are not > 6...
if (names [counter].equals(searchName)){
counter++;
foundName = true;
break;
}

Ok, IF you find a name, you increase the counter... But what happens if
you don't find one? In the next round, you will check the SAME name
again - and again - and again...

You must increase your counter, no matter if you found a name or not :)

Flo

Also, your for loop checked "i < names.length", perhaps your while
loop should use "count < names.length"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top