2016-07-02 5 views
3

Проблема в том, что я пишу в файл. Everytime, что я сделан давая значения строк в консоли, это даст мне ошибку следующим образом:Ошибка при попытке записи в файл?

Exception in thread "main" java.lang.IllegalStateException: Scanner closed 
at java,util,Scanner,ensureOpen(Unknown Source) 
at java,util,Scanner,findWithinHorizon(Unknown Source) 
at java,util,Scanner,hasNextLine(Unknown Source) 
at mainPackage,MainClass,main(MainClass.java:71) 

Это мой код:

package mainPackage; 

import java.util.Scanner; 
import java.util.concurrent.ThreadLocalRandom; 
import java.util.ArrayList; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.BufferedWriter; 

public class MainClass { 

    private static FileWriter fw; 
    private static BufferedWriter out; 
    private static Scanner input; 
    private static Scanner file; 
    private static FileWriter fw2; 
    private static BufferedWriter out2; 
    private static Scanner file2; 
    private static ArrayList<String> questList; 
    private static ArrayList<String> ansList; 

    public static void main(String[] args) throws IOException , IllegalStateException{ 

     fw = new FileWriter("C:/Users/ALAN_BARE/Desktop/Dictionary.txt" , true); 
     input = new Scanner(System.in); 
     file = new Scanner(new File("C:/Users/ALAN_BARE/Desktop/Dictionary.txt")); 
     out = new BufferedWriter(fw); 
     fw2 = new FileWriter("C:/Users/ALAN_BARE/Desktop/Dictionary2.txt" , true); 
     out2 = new BufferedWriter(fw2); 
     file2 = new Scanner(new File("C:/Users/ALAN_BARE/Desktop/Dictionary2.txt")); 
     questList = new ArrayList<String>(); 
     ansList = new ArrayList<String>(); 

     String engword; 
     String gerword; 
     String response; 
     int counter = 0; 

     //Loading the file data to the arraylist 
     while (file.hasNextLine()) { 
     questList.add(file.nextLine()); 
     ansList.add(file2.nextLine()); 
     } 

     file.close(); 
     file2.close(); 

     System.out.println("What do you want to do, register words or Play the game?"); 
     response = input.nextLine(); 

     //Getting the values of the strings via user input 
     if (response.contains("register")) { 

     System.out.println("Type yor english word:"); 
     engword = input.nextLine(); 
     System.out.println("Type the translation in German:"); 
     gerword = input.nextLine(); 

     //writing it to a file 
     if (file.hasNextLine()) { 
      out.newLine(); 
      out.write(engword); 
     } 
     else { 
      out.write(engword); 
     } 

     if (file2.hasNextLine()) { 
      out2.newLine(); 
      out2.write(gerword); 
     } 
     else { 
      out2.write(gerword); 
     } 
     } 

     //The same, just for a different response 
     else if (response.contains("Register")) { 
     System.out.println("Type yor english word:"); 
     engword = input.next(); 
     System.out.println("Type the translation in German:"); 
     gerword = input.next(); 

     if (file.hasNextLine()) { 
      out.newLine(); 
      out.write(engword); 
     } 
     else { 
      out.write(engword); 
     } 

     if (file2.hasNextLine()) { 
      out2.newLine(); 
      out2.write(gerword); 
     } 
     else { 
      out2.write(gerword); 
     } 
     } 

     out.close(); 
     out2.close(); 

     //Running the quiz game 
     if (response.contains("play")) { 

      while (counter <= 10) { 
       counter++; 
       int sel = ThreadLocalRandom.current().nextInt(0, questList.size() + 1); 

       System.out.println("The english word is :" + questList.get(sel)); 
       System.out.println("Please type the translation in German:"); 
       String answer = input.nextLine(); 

       if (answer.contains(ansList.get(sel))) { 
        System.out.println("Correct!"); 
       } 
       else { 
        System.out.println("Wrong! You Lose! If you want to play again, restart the app."); 
        break; 
       } 
      } 
     } 

     while (counter == 10) { 
      System.out.println("You Win The Game! If you want to play again, restart the app."); 
      counter++; 
     } 
    } 
} 

Что может быть проблема?

+0

Поместите запятые в ошибке, чтобы сделать StackOverflow не признать его в качестве кода –

+0

Какая линия 71 (где происходит ошибка)? – markspace

+0

@markspace if (file.hasnextLine()) { –

ответ

2

Это нормально, что вы получите сообщение об ошибке после закрытия Scanner объекта с именем, как file в строке 56

file.close()

Ошибки Вы получаете решить проблему ясно.

Сканер закрыт

+0

Это объясняет ошибку, но не предлагает решения, которые могут быть полезны будущему читателю. В противном случае его краткое объяснение –

+0

@BenKnoble Решение не использовать сканер после его закрытия. Это настолько тривиально, что едва ли стоит говорить. – EJP

+0

Или оставить его закрытым, чтобы он не оставил его открытым для выполнения обработки и снова открыть его (создать новый) для записи в конце. Это было предложение; если бы я чувствовал себя сильно, я всегда мог добавить свой собственный ответ. –

Смежные вопросы