向列表中添加新对象;(循环工作不正常)



所以我试图从一个名为directory.txt的文件中向一个新列表添加一个名字,该文件有1000个对象,其中包含名字、姓氏和电话号码;像这样的东西(道奇,尼克765-123-2312)。当我在没有"for循环"的情况下运行下面的程序时,我可以成功地从.txt文件中添加第一个对象,并将其打印出来。然而,当我添加一个for循环时,比如for(int I=0;I<1000;I++),由于某种原因,它会跳到列表的末尾,在第一个位置输入1000对象,然后跳过其余部分。我想不通!谢谢你的帮助。

新代码;

 import java.io.File;
  import java.io.FileNotFoundException;
  import java.util.ArrayList;
  import java.util.Scanner;
  import bsu.edu.cs121.names.Names;
  import bsu.edu.cs121.quickSort.QuickSort;

   public class NameTester {

public static void main(String[] args)throws FileNotFoundException {

    ArrayList<Names> namelist= new ArrayList<Names>();
    Scanner file = new Scanner(System.in);
    System.out.println("Please enter the name of the phone book file: ");
    String newFile = file.next();
    File inputFile = new File("/Users/Latif/Desktop/workspace/CS121 Project4/src/" + newFile);
    Scanner readFile = new Scanner(inputFile);
    while (readFile.hasNextLine()){ //start while
                String lastName = readFile.next();
                String firstName = readFile.nextLine();
                String phoneNumber = readFile.nextLine();
                namelist.add(new Names(firstName, lastName, phoneNumber));

    }

    QuickSort newSort = new QuickSort(namelist);
    System.out.println(namelist.get(1) + " " +  namelist.get(2));


}

}

因为每次都要将名称数据插入到名称列表数组的索引[0]中,所以每次循环都要替换以前的数据,最后会得到一个与最后一个条目相等的项。您需要为每个数组分配适当的数组索引。

nameslist[i] = new Names(first, last, number);

最新更新