简体   繁体   English

我如何计算java循环中的平均年龄?

[英]how can i calculate the average age in a java loop?

I was asked to write a program that ask a health worker to enter the info of the patients he helps each day.我被要求编写一个程序,要求卫生工作者输入他每天帮助的患者的信息。 But I couldn't calculate the average of the entered age and show the info of which patient is the oldest and who is the youngest.但是我无法计算输入年龄的平均值并显示哪个患者年龄最大,谁年​​龄最小的信息。 Can anyone help me with this please, I've done the first steps correctly but I don't know how to do the rest.任何人都可以帮我解决这个问题,我已经正确地完成了第一步,但我不知道如何做剩下的。

public static void main(String[] args) {
    int i, i2, i4, a;
    String s1, s2, s3, s4;

    s1 = JOptionPane.showInputDialog("Enter The Number Of Patients");
    i = Integer.parseInt(s1);
    a = 0;
    while (a < i) {
        s2 = JOptionPane.showInputDialog("Enter patient's ID");
        i2 = Integer.parseInt(s2);
        s3 = JOptionPane.showInputDialog("Enter patient's Name");

        s4 = JOptionPane.showInputDialog("Enter patient's Age");
        i4 = Integer.parseInt(s4);

        JOptionPane.showMessageDialog(null, " ID : " + i2 + "\n Name : " + s3 + "\n Age : " + i4);

        a++;
    }
}

The comments are good.评论很好。 That said, the simplest way would be as follows:也就是说,最简单的方法如下:

public static void main(String[] args) {
    int i, i2, i4, a;
    String s1, s2, s3, s4;

    s1 = JOptionPane.showInputDialog("Enter The Number Of Patients");
    i = Integer.parseInt(s1);
    a = 0;
    long totalAges = 0;
    while (a < i) {
        s2 = JOptionPane.showInputDialog("Enter patient's ID");
        i2 = Integer.parseInt(s2);
        s3 = JOptionPane.showInputDialog("Enter patient's Name");

        s4 = JOptionPane.showInputDialog("Enter patient's Age");
        i4 = Integer.parseInt(s4);

        JOptionPane.showMessageDialog(null, " ID : " + i2 + "\n Name : " + s3 + "\n Age : " + i4);

        totalAges += i4;
        a++;
    }

    double avgAge = ((double) totalAges) / i;
    JOptionPane.showMessageDialog(null, " Average Age: " + avgAge);
}

You can use List interface for storing all the patients age.您可以使用List接口存储所有患者的年龄。

Code is like:代码是这样的:

List<Integer> myPatientAge = new List<Integer>();

myPatientAge.add(i4);


Iterator<Integer> myListIterator = myPatientAge.iterator(); 
while (myListIterator.hasNext()) {
    Integer age = myListIterator.next(); 
    //code for checking the age    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM