本文介紹了如何將一個數組輸入與另一個數組輸入相關聯?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
假設我有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.");
}
推薦答案
假設您的數組具有相同的大小和與名稱對應的期限,那么您可以檢查最高期限并存儲具有最高期限的元素的索引。
那么您的名字就在這個指示符上。
int highestAgeIndice = 3; //indice of element with age 97 as example
names[highestAgeIndice] // the corresponding name
計算最高年齡并存儲其索引
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
代碼
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;
for (int i = 0; i < entries; i++) {
System.out.println("How old is " + name[i] + " ?");
age[i] = input.nextInt();
ageSum += age[i];
}
int max = 0;
int highestInd = 0;
for (int i = 0; i < age.length; i++) {
if (age[i] > max) {
max = age[i];
highestInd = i;
}
}
System.out.println("the oldest person is " +
name[highestInd] + " whose " + max + " years old.");
}
這篇關于如何將一個數組輸入與另一個數組輸入相關聯?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,