[英]how do i match the index of two parallel arrays?
我在文本文件中有一個在名稱和年齡之間交替的列表。 有9個名字和9個年齡。
我需要我的程序才能顯示
人(在此插入姓名)的年齡最高:(在此插入年齡)。
到目前為止,這是我的代碼:
public class Names
{
public static void main(String[] args) throws Exception
{
// get textfile
Scanner input = new Scanner( new File("names_and_ages.txt") );
final String[] names= new String[9];
final int[] ages= new int[9];
int counter = 0;
while (input.hasNext()) //while not end-of-file
{
names[counter]=input.next();
ages[counter]=Integer.parseInt(input.next());
counter++;
}
highestAge(names, ages);
input.close();
}//end of main
public static void highestAge (String[] name, int[] age)
{
String name;
int count = 0;
int oldest = highestAge[count];
for ( int number: highestAge)
{
if (number > oldest)
{
oldest = number;
}
}
System.out.print("Person " + name + " has the highest age: " + oldest );
}//end of Size method
}//end of class
一切都編譯了,我只是看不到使名稱與年齡匹配。 救命?
如果創建了Person類,則可以省去管理兩個數組的麻煩。
這將是您的Person類:
class Person {
String name;
int age;
}
public static void highestAge(String[] names, int[] ages)
{
//SET SENSIBLE DEFAULTS TO oldest AND index
int index = 0;
int oldest = ages[0];
//Looping based on index
for (int i = 0; i < ages.length; i++)
{
if (ages[i] > oldest)
{
index = i;
oldest = ages[i];
}
}
System.out.print("Person " + names[index] + " has the highest age: " + ages[index] );
}//end of Size method
你不遠。 您需要維護最舊的年齡的“索引”,然后可以使用它在兩個數組之間進行引用。
public static void highestAge (String[] names, int[] ages)
{
String name
int oldest = 0;
int oldestIndex = -1;
for (int index = 0; index < ages.length; index++)
{
if (ages[index] > oldest)
{
oldest = number;
oldestIndex = index;
}
}
System.out.print("Person " + names[oldestIndex] + " has the highest age: " + oldest );
}//end of Size method
另外,我不知道您的示例如何編譯,我看不到highestAge
數組highestAge
任何地方聲明了:P
就個人而言,我將創建一個名稱和年齡作為字段的Person
類。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
然后,我將在循環的每次迭代中創建一個新的Person
並將它們添加到人員數組中( Person[] people = new Person[...]
)(實際上,我將使用java.util.list
的實現java.util.list
但就是我)
突然間,您將獲得大量創造力。
您可以提供isOlderThen(Person person)
方法來比較人們。
if (person.isOlderThen(oldest)) {
oldest = person;
}
您實際上只是使用Arrays.sort
和Comparator
根據每個人的年齡對數組進行Arrays.sort
1)創建一個類
class person
{
String name;
int age;
}
2)僅創建一個數組:Person []人
3)重寫方法highestAge
Person getOldest( Person[] persons )
{
Person oldest = null;
for( Person person : persons )
{
if( oldest == null || person.age > oldest.age )
{
oldest = person;
}
}
return oldest;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.