有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

  1. # 1 楼答案

    你把nextLinenext搞混了。用hasNext()替换你的hasNextLine(),你应该没事了