我目前正在尝试从我的硬盘读取文件。文件名为“Sample.txt”,下面是我的代码。我能够编译并运行它,但收到此错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Proj1GradesService.errorReport(Proj1GradesService.java:42)
at Proj1GradesClient.main(Proj1GradesClient.java:13)
我试过只用 While 循环读取文件,现在用 try/catch 读取文件,但收到了同样的错误,我不确定它到底出了什么问题。我正在尝试从服务类读取文件并从客户端类调用方法 errorReport()。 任何帮助将不胜感激。
import java.util.*; //allows use of Scanner class
import java.io.*; //for File and IOException classes
class Proj1GradesService
{ //begin Proj1GradesService
public void pageAndColHeading(char letter) //accepts char as a parameter
{ //start pageAndColHeading
switch (letter)
{ //start switch
case 'e': //write the caption for error report
System.out.println ("Error Report - Students With Invalid GPA"); //prints Error Report
break;
case 'v': //write the caption for valid report
System.out.println ("Valid Report - Students With Valid"); //prints Valid Report
break;
default: ; //do nothing
}//end switch
} //end pageAndColHeading
public void errorReport() throws IOException
{ //start errorReport
Scanner scanFile = null;
try
{
scanFile = new Scanner (new File ("p1SampleGPAData.txt"));
}
catch (FileNotFoundException fnfe)
{
System.out.println ("wrong file name.");
}
String name; //name read from file
double gpa; //gpa read from file
int count = 0; //line #
while (scanFile.hasNext( ))
{
name = scanFile.next();
gpa = scanFile.nextDouble();
System.out.println ("Line Number: " + count + "Name: " + name + "GPA: " + gpa);
++count;
} //end while
scanFile.close();
} //end errorReport
} //end class
最佳答案
考虑下面从打印语句假定的文件结构
name1 1.1
name2 2.2
name3 3.3
现在根据您的代码以下行
// consume your whole line. ie name1 1.1
name = scanFile.next();
// looking for double but instead getting string ie name2
// hence throwing InputMismatchException
gpa = scanFile.nextDouble();
现在解决上述问题。您可以使用 String.split()
.
// collect whole line
name = scanFile.next();
// split by one or more whitespace OR use your delimiter
String[] str = name.split("\\s+");
// gives name
String actName = str[0];
// gives gpa, throws NumberFormatException if str[1] is not double value
double gpa = Double.parseDouble(str[1]);
希望对您有所帮助。如果您需要更多帮助,请直接提出。
关于java.util.InputMismatchException 输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201086/