2014-11-14 182 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.