2016-03-13 3 views
-2

Итак, я пытаюсь прочитать весь файл и распечатать его содержимое, которое он делает. Но когда я снова просмотрю его с помощью нового сканера для печати содержимого с именами некоторых разделов, он проходит только через некоторый файл.Java Scanner не будет читать весь файл

Вот мой код:

import java.util.*; 
import java.io.*; 


public class FileReader { 
    public static void main(String[] args) throws FileNotFoundException { 
     Scanner read = new Scanner(new File("sample.txt")); 

     while(read.hasNextLine()) { 
     System.out.println(read.nextLine()); 
     } 
     System.out.println(); 

     Scanner read2 = new Scanner(new File("sample.txt")); 
     int numQuestions = read2.nextInt(); 
     System.out.println("Numbers of questions: " + numQuestions); 
     System.out.println(); 

     while(read2.hasNextLine()) { 
     int points, numChoices; 
     String question, answer; 

     if(read2.next().equals("TF")) { 
      points = read2.nextInt(); 
      System.out.println("Points for TF: " + points); 
      read2.nextLine(); // must be done because it does not consume the \n character 
      question = read2.nextLine(); 
      System.out.println("Question for TF: " + question);  
      answer = read2.next(); 
      System.out.println("Answer for TF: " + answer); 
     } 
     else if(read2.next().equals("SA")) { 
      points = read2.nextInt(); 
      System.out.println("Points for SA: " + points); 
      read2.nextLine(); // must be done because it does not consume the \n character 
      question = read2.nextLine();    
      System.out.println("Question for SA: " + question); 
      answer = read2.next(); 
      System.out.println("Answer for SA: " + answer); 
     } 
     else if(read2.next().equals("MC")) { 
      points = read2.nextInt(); 
      System.out.println("Points for MC: " + points); 
      read2.nextLine(); // must be done because it does not consume the \n character 
      question = read2.nextLine(); 
      System.out.println("Question for MC: " + question); 
      read2.nextLine(); 
      numChoices = read2.nextInt(); 
      for(int i = 0; i < numChoices; i++) { 
       System.out.println(read2.nextLine()); 
      } 
      answer = read2.next(); 
      System.out.println("Answer for MC: " + answer); 
     } 
     } 
    } 
} 

Вот файл я читаю от:

3 
TF 5 
There exist birds that can not fly. (true/false) 
true 
MC 10 
Who was the president of the USA in 1991? 
6 
Richard Nixon 
Gerald Ford 
Jimmy Carter 
Ronald Reagan 
George Bush Sr. 
Bill Clinton 
E 
SA 20 
What city hosted the 2004 Summer Olympics? 
Athens 

А вот выход я получаю:

3 
TF 5 
There exist birds that can not fly. (true/false) 
true 
MC 10 
Who was the president of the USA in 1991? 
6 
Richard Nixon 
Gerald Ford 
Jimmy Carter 
Ronald Reagan 
George Bush Sr. 
Bill Clinton 
E 
SA 20 
What city hosted the 2004 Summer Olympics? 
Athens 

Numbers of questions: 3 

Points for TF: 5 
Question for TF: There exist birds that can not fly. (true/false) 
Answer for TF: true 

Как вы можете видеть , первый Scanner читает весь файл и печатает его. Но когда я пытаюсь во второй раз с именами разделов, он проходит только часть вопроса 1.

+0

Вы используете «Сканер чтения» только один раз, а затем создаете второй объект типа «Сканер read2'. Если вам больше не нужно «читать», вы должны использовать эту же переменную для создания нового объекта Scanner: 'read = new Scanner (новый файл (« sample.txt »));'. В этом случае у вас меньше переменных, а код легче читать. – Victor1125

ответ

1

Я думаю, что это потому, что вы сканируете 3 раза с помощью инструкции else-if, поэтому вы должны создать переменную String type = read2.next(); и использовать ее в if-else.

0

Как известно, read2.next() читает следующее слово. Когда вы вызываете его более одного раза, он читает более одного слова.

Так что, когда вы делаете

// read a word, and if it's not TF, discard it. 
if(read2.next().equals("TF")) { 

// read another word, and it it's not SA discard it. 
else if(read2.next().equals("SA")) { 

Что вы хотели, чтобы прочитать слово один раз, и сравнить его несколько раз. Простой способ сделать это - использовать переключатель.

// read once, 
switch(read.next()) { 
    case "TF": 
     // do something 
     break; 

    case "SA": 
     // do something 
     break; 

    // more case(s) 
} 
Смежные вопросы