如何在消息框中显示变量的值?

时间:2013-03-17 09:30:18

标签: java

我想显示“姓名数量”。假设我输入两个名字,它应显示“”你输入了两个名字。

导入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");

}
}

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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");

}
}