2016-10-08 7 views
1

コードは、ファイルから文字列の配列を読み込み、それを印刷することになっています。私はコードに何が間違っているのか分かりません。ファイルから文字列を読み取ることができないのはなぜですか?

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class program2 { 

    public static void main(String[] args) throws IOException { 
     //PriorityQueue<String> q = new PriorityQueue<String>(); 
     //file that contains strings 
     File file = new File("infix.txt"); 
     Scanner scnf = new Scanner(file); 
     // array count 
     int arycnt = 0; 
     // gets the count of the array in the file 
     while(scnf.hasNextLine()){ 
      arycnt++; 
      scnf.next(); 
     } 
     // creates array 
     String[] letter = new String[arycnt]; 
     //reads in array from file 
     Scanner scnf2 = new Scanner(file); 
     for(int i = 0; i<arycnt ;i++){ 
      letter[i] = scnf2.next(); 
     } 
     // suppose to print all of the array 
     for (int i = 0;i < letter.length;i++){ 
      System.out.println(letter[i]); 
     } 

    } 

} 
+1

あなたは2つの 'Scanner'オブジェクトを決して閉じないので、リソースが漏れています。また、 'String []'の代わりに 'ArrayList 'を使うことをお勧めします。そのため、ファイルを2度読む必要はありません。 – Andreas

答えて

2

あなたはnextLinenextの間で混同されています。 hasNextLine()hasNext()に交換してください。問題ありません。

+1

ファイル内の "文字列"がそれぞれ独自の行にあるか、空白で区切られた "トークン"であるかによって 'next()'を 'nextLine()'に置き換えてください。 – Andreas

関連する問題