Rss & SiteMap

课外天地 李树青 http://www.njcie.com

李树青 论坛 南京 财经 课外天地
共1 条记录, 每页显示 10 条, 页签: [1]
[浏览完整版]

标题:程序代码——要求用户输入任意个数,以输入0结束,并打印平均值

1楼
admin 发表于:2006/2/26 21:32:40

public class exec
{
        public static void main( String args[] ) throws Exception
        {
                int amount=0;
                int counter=0;
                
                while(true)
                {
                        int i=Integer.parseInt(javax.swing.JOptionPane.showInputDialog("Please input the number(end with zero)"));
                        if(i==0)
                                break;
                        amount=amount+i;
                        counter++;
                }
                
                String str=String.valueOf((double)amount/counter);
                javax.swing.JOptionPane.showMessageDialog(null,str);
                
                System.exit(0);
        }
}

对于退出循环的比较可以直接使用字符串比较,方法是利用String变量中的equals方法,而不是 s=="0"
public class exec
{
        public static void main( String args[] ) throws Exception
        {
                int amount=0;
                int counter=0;
                
                while(true)
                {
                        String s=javax.swing.JOptionPane.showInputDialog("Please input the number(end with zero)");
                        
                        if(s.equals("0"))
                                break;
                                
                        int i=Integer.parseInt(s);              
                        amount=amount+i;
                        counter++;
                }
                
                String str=String.valueOf((double)amount/counter);
                javax.swing.JOptionPane.showMessageDialog(null,str);
                
                System.exit(0);
        }
}

[此贴子已经被作者于2010-12-12 07:37:48编辑过]
共1 条记录, 每页显示 10 条, 页签: [1]

Copyright ©2002 - 2016 课外天地.Net
Powered By Dvbbs Version 8.3.0
Processed in .03125 s, 2 queries.