No break in while loop. That is one problem. However you are getting an
ArrayIndexOutOfBounds exception because you are incrementing I before
accessing the array. Hence you are trying to access i[8] which does not
exist. You have to increment i (i++) after accessing the array. If you had
a break it would go out. It doesn't solve completely the problem.
// my while loop code
int i = 0;
while (i<names.length){
i++; // this is wrong here. You should put this
after accessing the array.
if (names [i].equals(searchName)){
foundName = true;
break;
}
}
// for loop code
//for (int i=0; i<names.length; i++){
// if (names [i ].equals(searchName)){
// foundName =true;
// break;
// }
// }
From: [email protected]
[mailto:[email protected]] On Behalf Of Charles
Polidano
Sent: Wednesday, September 16, 2009 1:38 PM
To: [email protected]
Subject: [java programming] Homewrok Topic 2 - Control Structures = Please
HELP
Hi all
I am emcounterig problems when trying to convert the for loop into a while
loop.
The following is the program code of the for loop, i have tried many
statements but without success.
Your help will be really appreciated.
Many thanks
import javax.swing.JOptionPane;
/**
*
* @author Compuline
*/
public class OwnWhile {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String names
[]={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};
String searchName = JOptionPane.showInputDialog("Enter either
\"Yza\" or \"noname\"!");
// Declare and initialize boolean primitive type variable calld
foundName.
boolean foundName =false;
// my while loop code
int i = 0;
while (i<names.length){
i++;
if (names [i].equals(searchName)){
foundName = true;
}
}
// for loop code
//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!");
}
}
_____
check out the rest of the Windows LiveT. More than mail-Windows LiveT goes
way beyond your inbox. More than
<http://www.microsoft.com/windows/windowslive/> messages
No virus found in this incoming message.
Checked by AVG - www.avg.com
Version: 8.5.409 / Virus Database: 270.13.100/2375 - Release Date: 09/16/09
05:51:00
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---