找到最低年龄并从文件中打印出数组中的相应名称?

时间:2014-11-11 17:48:00

标签: java

我需要帮助从名为Stuff.txt的文件中读取名称和年龄的程序。我能够打印两个数组,但我还需要找到最低年龄并打印出相应的名称。我的代码不起作用,我不明白为什么?无需循环或开关。我的东西。 TXT"到目前为止包含以下输入:

  Sam 21 Ram 22 Hero 23

以下是我迄今为止所做的工作:

 import java.io.*;
 import java.util.*;
 public class nameAge
 {
public static void main(String[] args) throws FileNotFoundException
{
  ArrayList<String> names = new ArrayList<String>();
  ArrayList<Integer> ages = new ArrayList<Integer>();

  Scanner inFile = new Scanner(new File("stuff.txt")); 
  int i = 0; 
  while (inFile.hasNextLine()) { 
  String line = inFile.nextLine();
  Scanner lineScanner = new Scanner(line); 
  while(lineScanner.hasNext()){
  names.add(lineScanner.next());
  ages.add(lineScanner.nextInt());
  }
   System.out.println(names);
   System.out.println(ages);
  }


   int idx = -1;  
   int d= 100000;  
   for( i = 0; i < 3; i++) 
     if(ages < d) 
   { 
     d = ages[i]; 
     idx = i; 
   } 
   System.out.println("Lowest age "+ ages[idx] + "Corresponding Name" + name[idx] ); 

  }
  }

2 个答案:

答案 0 :(得分:2)

遍历您的年龄列表,该索引是您姓名中的索引,因为年龄和姓名之间的比率为1:1。

请求的完整代码。

public static void main(String[] args){
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> ages = new ArrayList<Integer>();

        //YOUR LOADING CODE GOES HERE

        int index = getIndexOfMin(ages);
        System.out.println(names.get(index) + " is " + ages.get(index));

    }

    public static int getIndexOfMin(ArrayList<Integer> data) {
        float min = Float.MAX_VALUE;
        int index = -1;
        for (int i = 0; i < data.size(); i++) {
            Integer f = data.get(i);
            if (Float.compare(f.floatValue(), min) < 0) {
                min = f.floatValue();
                index = i;
            }
        }
        return index;
    }

答案 1 :(得分:1)

略微修改ExcelledProducts发布的代码

import java.io.*;
import java.util.*;

public class NameAge {

public static void main(String[] args) throws FileNotFoundException
{
  ArrayList<String> names = new ArrayList<String>();
  ArrayList<Integer> ages = new ArrayList<Integer>();

  Scanner inFile = new Scanner(new File("stuff.txt")); 
  int i = 0; 
  while (inFile.hasNextLine()) { 
  String line = inFile.nextLine();
  Scanner lineScanner = new Scanner(line); 
  while(lineScanner.hasNext()){
  names.add(lineScanner.next());
  ages.add(lineScanner.nextInt());
  }
   System.out.println(names);
   System.out.println(ages);
  }

  int old_age = 0;
  int old_age_i = 0;
  int count = 0;
  for(int age : ages){
       if (old_age == 0)
            old_age = age;
       else
            if (old_age > age){
                 old_age = age;
                 old_age_i = count;
       count ++;}
            else continue;
  }
  String name = names.get(old_age_i);
  System.out.println(name);
  String theAge = ages.get(old_age_i);
  System.out.println(theAge);
  }
}