2013-03-17 76 views
0

我想显示“人数”。假设我输入两个名字,它应该显示“”你输入了两个名字。如何在消息框中显示变量的值?

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

} 
} 
+0

你的问题到底是什么? – ffledgling 2013-03-17 09:31:37

+2

@ C.Lang当我发表评论时,所有问题都是“如何计算循环次数?”然后在问题描述中有代码。 :) – ffledgling 2013-03-17 09:38:06

+0

谢谢你的回复。我正在试图自己来解决这个问题。其实,我刚刚加入了stackoverflow,因为我不能自己来确定。我的问题是,我想显示showMessageDialog中的名称数量。 – user2178940 2013-03-17 09:38:37

回答

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

+0

你的计数器是关闭的。 – 2013-03-17 09:33:16

+2

为什么这是一个社区维基? – 2013-03-17 09:33:27

+0

@JBNizet计数器似乎正确计算了迭代次数,这似乎是问题(OP的代码缺少输入名称的部分)。 – 2013-03-17 09:37:00

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

} 
} 
+0

您的计数器已关闭。 – 2013-03-17 09:33:56