将新对象添加到列表中; (对于循环不正常)

时间:2013-07-11 23:08:51

标签: java loops object for-loop add

所以我正在尝试从名为directory.txt的文件中添加名称到新列表,该文件包含1000个包含名字,姓氏和电话号码的对象;这样的事(道奇,尼克765-123-2312)。当我在没有“for循环”的情况下运行下面的程序时,我可以成功地将第一个对象添加到.txt文件中并将其打印出来。然而,当我添加一个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));




}

}

1 个答案:

答案 0 :(得分:1)

因为您每次都将名称数据插入名单列表数组的索引[0],所以每个循环都要替换以前的数据,最后一个项目最后会有一个等于上一个条目的项目。您需要为每个分配正确的数组索引。

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