本文介紹了如何將一個(gè)數(shù)組輸入與另一個(gè)數(shù)組輸入相關(guān)聯(lián)?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
假設(shè)我有2個(gè)掃描儀填充的數(shù)組,name[]
和age[]
。每一張都是按順序填寫(xiě)的。如果我要查找數(shù)組中年齡最大的人,我如何使用數(shù)組打印出他們的姓名和年齡?
例如,age[]
中最大的條目是78
。有沒(méi)有辦法將其與name[]
數(shù)組關(guān)聯(lián)以將其打印出來(lái)?
參考編碼:
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.");
}
推薦答案
假設(shè)您的數(shù)組具有相同的大小和與名稱(chēng)對(duì)應(yīng)的期限,那么您可以檢查最高期限并存儲(chǔ)具有最高期限的元素的索引。
那么您的名字就在這個(gè)指示符上。
int highestAgeIndice = 3; //indice of element with age 97 as example
names[highestAgeIndice] // the corresponding name
計(jì)算最高年齡并存儲(chǔ)其索引
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.");
}
這篇關(guān)于如何將一個(gè)數(shù)組輸入與另一個(gè)數(shù)組輸入相關(guān)聯(lián)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,