我被要求编写一个程序,要求医务人员输入他每天帮助的病人的信息。但是,我无法计算输入年龄的平均值,并显示哪个患者是最老的,哪个是最年轻的。任何人都可以帮我解决这个问题,我已经正确地完成了第一步,但我不知道如何做其余的事。
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++;
}
}
答案 0 :(得分:2)
评论很好。也就是说,最简单的方法如下:
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);
}
答案 1 :(得分:0)
您可以使用List
界面存储所有年龄的患者。
代码就像:
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
}