【发布时间】:2021-05-15 14:22:17
【问题描述】:
假设我有 2 个扫描仪填充数组,name[] 和 age[]。每个都按顺序填写。如果我要找到数组中最年长的人,如何使用数组打印出他们的姓名和年龄?
例如age[] 中最大的条目是78。有没有办法将它与name[] 数组关联起来打印出来?
参考代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many entries ?");
int entries;
do {
entries = input.nextInt();
if (entries < 1) {
System.out.println("please enter a valid number!");
}
} while (entries < 1);
String[] name = new String[entries];
String[] gender = new String[entries];
int[] age = new int[entries];
for (int i = 0; i < entries; i++) {
System.out.println("Enter the name of person No" + (i + 1) + ".");
name[i] = input.next();
}
double ageSum = 0;
int max = 0;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
max = Math.max(max, age[i]);
}
System.out.println("the oldest person is "
+ name[] + " whose " + max + " years old.");
}
【问题讨论】:
标签: java arrays sorting java.util.scanner