输入未知数量的单词,直到输入另一个单词

时间:2014-03-03 07:03:57

标签: java string loops integer counting

在输入字符串“@@@”之前,如何输入未知数量的名称?当完成后,我如何计算在程序结束之前输入的名称数量。

如果可能,请更正:

    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.");

3 个答案:

答案 0 :(得分:4)

试试这个:

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

答案 1 :(得分:0)

你可以使用像这样的do-while循环来实现。

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);

希望这有帮助。

答案 2 :(得分:0)

在while循环结束时插入以下内容:

if (newname.equals(end)) found = true;