Question

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.");
Was it helpful?

Solution

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

OTHER TIPS

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.

insert the following at the end of your while loop:

if (newname.equals(end)) found = true;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top