0

我想显示“名字的数量”。假设如果我输入两个名字,它应该显示“”你输入了 2 个名字。

导入 javax.swing.JOptionPane;

public class MyName {
public static void main (String args [ ])

{
    int option;
    String userName;

    do
    {
        option = JOptionPane.showConfirmDialog(null,"Want to enter another Name?");

    } while (option == JOptionPane.YES_OPTION);

    JOptionPane.showMessageDialog(null, "you have entered" + (number of names) + "names");

}
}
4

2 回答 2

3

要计算迭代次数,您可以这样做:

int i=0; // create a counter
do {
    option = JOptionPane.showConfirmDialog(null,"Want to enter another useraName?");
    i++; // increment the counter
} while (option == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null, "you have entered " + i + " names"); // use it

但通常,你不会有这个问题,因为你应该存储名称:

List<String> names = new ArrayList<>();
do {
     ...
     names.add(enteredName);
while ...

循环之后,名称的数量为names.size()

于 2013-03-17T09:31:42.003 回答
1

通过使用变量?

import javax.swing.JOptionPane;

public class MyName {
public static void main (String args [ ])

{
    int option;
    String userName;

    int number = 0;
    do
    {
        number++;
        option = JOptionPane.showConfirmDialog(null,"Want to enter another useraName?");

    } while (option == JOptionPane.YES_OPTION);

    JOptionPane.showMessageDialog(null, "you have entered" + (number of names) + "number");

}
}
于 2013-03-17T09:32:12.450 回答