2014-01-20 42 views
0

我已經編寫了此代碼以讀取文件,然後爲文件中的每個名稱請求一個標記。如果標記超過40,則其合格和以下是失敗並將每個名稱寫入相應的文件。但我會在線路27的錯誤:while(namesFile.hasNext()這裏是我的代碼:正在讀取和寫入文本文件

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

public class TestResults { 
    public static void main(String[] args) { 
     String errs = ""; 
     Scanner k = new Scanner(System.in); 

     try { 
      try (
        Scanner namesFile = new Scanner(new File("Names.txt")); 

        PrintWriter passFile = new PrintWriter("Pass.txt"); 
        PrintWriter failFile = new PrintWriter("Fail.txt");) { 

       while (namesFile.hasNext()) { 
        try { 
         String tempLine = namesFile.nextLine(); 
         System.out.println("Please Enter Mark For " + tempLine + " : "); 
         int mark = k.nextInt(); 
         if (mark >= 40) { 
          passFile.println(tempLine + " " + mark + "%"); 
         } else { 
          failFile.println(tempLine + " " + mark); 
         } 
        } catch (InputMismatchException ime) { 
         String valueStr = namesFile.next(); 
         errs += "\n\t" + valueStr; 
        } finally { 
         namesFile.close(); 
         passFile.close(); 
         failFile.close(); 
        } 
       } 
      } 
     } // Checks to see if file is there. 
     catch (IOException ioe) { 
      System.out.println("ERROR: " + ioe.getMessage()); 
     } 
    } 
} 
+3

是什麼錯誤消息說? – Fildor

+2

爲什麼有{try(? – Rahul

+0

使你的代碼正確 – Rahul

回答

1
public class TestResults { 

    public static void main(String[] args) { 
    Scanner namesFile; 
    PrintWriter passFile; 
    PrintWriter failFile; 


    String errs = ""; 
    Scanner k = new Scanner(System.in); 

    try { 
     try { 
       namesFile = new Scanner(new File("D:/Names.txt")); 

       passFile = new PrintWriter("D:/Pass.txt"); 
       failFile = new PrintWriter("D:/Fail.txt"); 



       try { 
        while (namesFile.hasNext()) { 
        String tempLine = namesFile.nextLine(); 
        System.out.println("Please Enter Mark For " + tempLine + " : "); 
        int mark = k.nextInt(); 
        if (mark >= 40) { 
         passFile.println(tempLine + " " + mark + "%"); 
        } else { 
         failFile.println(tempLine + " " + mark); 
        } 
        } 
       } catch (InputMismatchException ime) { 
        String valueStr = namesFile.next(); 
        errs += "\n\t" + valueStr; 
       } finally { 
        namesFile.close(); 
        passFile.close(); 
        failFile.close(); 
       } 



     } 
     catch(IOException ioe){ 
      System.out.println("ERROR: " + ioe.getMessage()); 
     } 



    } // Checks to see if file is there. 
    catch (Exception e) { 

    } 

    } 
} 
+0

你在這裏有什麼改進? SomeSickJoke代碼中的 – Fildor

+0

namesFile不在while()的範圍內。這是錯誤。並且他在while循環中寫了最後的塊。它使文件讀取單行並關閉流。所以第二行不能被讀取。我把while循環放在try塊中。它工作正常。 –

+0

是的。這是一個「試用資源」。請參閱[這裏](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)。 – Fildor