从命令行txt.file java填充数组

时间:2013-11-15 23:57:02

标签: java arrays file-io

我一直在尝试用字符串填充数组&把它分成不同的数组,但我一定不能正确阅读它,因为我的数组中没有任何内容?

File inf = FileUtil.openFile(args);  // open the file passedin in args
      Scanner fin = new Scanner(inf);


public static File readFileInfo(Scanner kb)throws FileNotFoundException


{
      String fileName = null;

  File inFile = null;

  do
  {
     System.out.print("Enter the name of the input file: ");
     fileName = kb.nextLine();
     inFile = new File(fileName);
  }while(!inFile.exists());  

  return inFile;


}// end readFileInfo


 public static Author[] fillArray(Scanner fin)
{
      Author[] array = new Author[100];
      String first_ = null;
      String last_ = null;
      String publisher_ = null;
      int x = 0;

  while(fin.hasNext())
  {  
     first_ = fin.nextLine();
     last_ = fin.nextLine();
     publisher_ = fin.nextLine();
     Author temp = new Author(first_, last_, publisher_);
     array[x] = temp;
     x++;
  }

  return array; 

1 个答案:

答案 0 :(得分:2)

也许问题是你检查是否还有一个令牌但是尝试获取三个令牌

while(fin.hasNext())  // CHECK IF WE HAVE ONE MORE TOKEN
{  
 first_ = fin.nextLine();      // FETCH THREE
 last_ = fin.nextLine();
 publisher_ = fin.nextLine();
 Author temp = new Author(first_, last_, publisher_);
 array[x] = temp;
 x++;
}

这可能导致异常和空数组。

相关问题