3

I have a few problems with my code. I want to be able to read input from a text file and take the strings from each line or between spaces and assign them to variables that I will pass to an object.

My first problem is that my program misreads one of my lines and omits the first letter from a variable, and the second problem is I don't know how to make my program read two strings on the same line and assign them to different variables.

    System.out.println("Input the file name of the text file you want to open:(remember .txt)");
    keyboard.nextLine();
    String filename=keyboard.nextLine();

    FileReader freader=new FileReader(filename);
    BufferedReader inputFile=new BufferedReader(freader);

    courseName=inputFile.readLine();

    while (inputFile.read()!= -1) {
        fName=inputFile.readLine(); 
        lName=inputFile.readLine();
        officeNumber=inputFile.readLine();
    }
    System.out.println(fName);
    Instructor inst=new Instructor(fName,lName,officeNumber);
    System.out.println(inst);
    inputFile.close();

}

I am not very good at using filereader and have tried to use the scanner keyboard method, but it lead me to even more errors :(

Output: Input from a file (F) or keyboard (K): F Input the file name of the text file you want to open: (remember .txt) test.txt un bun un bun won won's office number is null

text file: professor messor bun bun won won

4

3 に答える 3

3

で 1 行を読みreadLine()、 で分割したいと言いますwhitespace

だからあなたはこのようなことをしなければなりません

    String line=null;
    List<Course> courses = new ArrayList<>();
        while ((line = inputFile.readLine())!= null) {
            String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace 
            courseName = arrayLine[0]
            lName=arrayLine[1];
            officeNumber=arrayLine[2];
            list.add(new Course(courseName,lName,officeNumber));   
          // you sure want do something with this create an object for example

        }

 // in some part br.close();

ここに、ファイルの読み取り方法の例があります

于 2013-07-16T23:44:57.643 に答える
0

read()ループの状態で呼び出すとwhile、BufferedReader の「カーソル」が 1 文字進みます。ストリームを読み取れるかどうかを確認するためにこれを行うのではなく、ready()メソッドを使用します。

于 2013-07-16T23:44:43.287 に答える