Reputation: 15
How do I input an unknown quantity of names until the string "@@@" is typed in? And when that is complete, how would I count the number of names that have been input before the program ended.
Please correct this if possible:
String name = JOptionPane.showInputDialog("Enter in a name");
int count = 0;
int i = 0;
String end = "@@@";
boolean found = name.indexOf(end) >= 0;
while(found == false)
{
int newcount = count + 1;
String newname = JOptionPane.showInputDialog("Enter in a name");
}
System.out.println("You have stopped the program because your name has ' " + end + " ' in it.");
Upvotes: 1
Views: 81
Reputation: 7457
Try this:
int count = 0;
while(true) {
try {
String newname = JOptionPane.showInputDialog("Enter in a name");
if (newname.equals("@@@"))
break;
count++;
}catch (Exception e) {
//do something rational
}
}
System.out.println(count);//change this as you wish
Upvotes: 4
Reputation: 7773
insert the following at the end of your while loop:
if (newname.equals(end)) found = true;
Upvotes: 0
Reputation: 9946
You can do it by using a do-while loop something like this.
int count = 0;
String end = "@@@";
String name = null;
do {
name = JOptionPane.showInputDialog("Enter in a name");
count++;
} while(name.indexOf(end)==-1);
System.out.println("You have stopped the program because your name has ' " + end + " ' in it.")
System.out.println("Total Names Entered : " + --count);
Hope this helps.
Upvotes: 0