2014-11-14 153 views
3

我還是比較新的Java。我爲課程創建了這個程序,它給了我一個我從未得到過的錯誤。如果有人能夠幫助那會很好。謝謝!輸入不匹配異常?

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

public class grades { 

    public static void main(String[] args) throws IOException { 
     // Define file names 
     final String INPUT_FILE = "gradesinput.txt"; 
     final String OUTPUT_FILE = "gradesoutput.txt"; 


     // define variables 
     int grade; 
     String name = null, filename; 
     double value = 0; 
     String msg; 

     // Access the input/output files 
     File inputDataFile = new File(INPUT_FILE); 
     Scanner inputFile = new Scanner(inputDataFile); 
     FileWriter outputDataFile = new FileWriter(OUTPUT_FILE); 
     PrintWriter outputFile = new PrintWriter(outputDataFile); 
     System.out.println("Reading file " + INPUT_FILE + "\r\n" + 
          "Creating file " + OUTPUT_FILE); 

     // Read all of the values from the file 
     while (inputFile.hasNext()) { 
     grade = inputFile.nextInt(); 
     name = inputFile.nextLine(); 
     name = name.trim(); 

    } // End while 

     if(value >= 90)  
      {   
      msg = "OUTSTANDING"; 
      } 
      else if (value >= 70) 
      { 
      msg = "Satisfactory"; 
      } 


      if(value >= 90){  
       msg = "OUTSTANDING"; 
    }else{ 
    if(value >= 70){ 
        msg = "Satisfactory";         

    }else 
        msg = "FAILING"; 
       } 

      outputFile.println(value + " " + name + " " + msg); 
      outputFile.println("processed names"); 
      outputFile.println("between 70 and 89 inclusive"); 
      outputFile.close(); 

     } // End outputResults 
} // End class 

我得到這個錯誤:

Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:864) 
    at java.util.Scanner.next(Scanner.java:1485) 
    at java.util.Scanner.nextInt(Scanner.java:2117) 
    at java.util.Scanner.nextInt(Scanner.java:2076) 
    at grades.main(grades.java:37) 
+2

我假設你已經一派異常,找到[文件](https://docs.oracle.com/javase/7/docs/api/java /util/InputMismatchException.html):由掃描程序檢測以指示檢索到的標記與預期類型的​​模式不匹配,或標記超出預期類型的​​範圍._ - 您的問題是什麼? – Krease 2014-11-14 19:47:13

+0

'String name = null,filename;'那是正確的嗎? – ha9u63ar 2014-11-14 19:49:11

+0

請清除您的實際問題。 – Benvorth 2014-11-14 19:49:35

回答

3

錯誤是在這裏:grade = inputFile.nextInt();

您試圖讀取一個int,但該文件已在這個位置沒有INT。

documentation舉例:

Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.