为什么我不能从文件中读取字符串?

时间:2016-10-08 21:34:14

标签: java string file-io java.util.scanner

代码应该从文件中读取字符串数组然后将其打印出来。我不确定代码有什么问题。

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 个答案:

答案 0 :(得分:2)

您在nextLinenext之间混音。将hasNextLine()替换为hasNext(),您应该没问题。