【问题标题】:Entering an unknown number of words untill another word is entered输入未知数量的单词,直到输入另一个单词
【发布时间】:2014-04-04 03:19:50
【问题描述】:

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

如果可能,请更正:

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

【问题讨论】:

  • 你错过了一个大标签:java!请记住使用正确的标签,特别是在这种情况下它有很大的优势。

标签: java string loops integer counting


【解决方案1】:

您可以通过使用类似这样的 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);

希望这会有所帮助。

【讨论】:

  • 你的计数是错误的。即使输入@@@ 它也会增加
  • 请查看我使用--count 打印的最后一个sop。请不要在未阅读完整解决方案的情况下投反对票谢谢
  • 呃,抱歉没看到。虽然如果我没有看到,那么也许不是最好的?也许是 cmets?
【解决方案2】:

试试这个:

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

【讨论】:

  • 从问题的措辞来看,我想知道contains是否可能是更好的方法?
  • @user2310289:也许吧。取决于他/她的意愿。我明白你的意思,但我认为他完全使用'@@@'作为哨兵,而不是像'@@@abcfdsf'。在这种情况下,是的,contains 会更好。
【解决方案3】:

在您的 while 循环末尾插入以下内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2015-02-07
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多