简体   繁体   中英

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.

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    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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