Java 处理输入不匹配异常的问题

Java 处理输入不匹配异常的问题,java,inputmismatchexception,Java,Inputmismatchexception,有人能告诉我为什么我总是收到输入不匹配的异常吗?我一直在试图理解发生了什么,但似乎无法理解。假设程序读取高温输入文件,然后创建读取的温度直方图 import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class CoolWeather {

有人能告诉我为什么我总是收到输入不匹配的异常吗?我一直在试图理解发生了什么,但似乎无法理解。假设程序读取高温输入文件,然后创建读取的温度直方图

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class CoolWeather
{
    static JFileChooser selecter;
    static Scanner in;
    public static void main(String[] args) throws FileNotFoundException
    {
       File inputFile;
       selecter = new JFileChooser(".");
       int status = selecter.showOpenDialog(null);
       if(status != JFileChooser.APPROVE_OPTION) 
       {
            JOptionPane.showMessageDialog(null, "Closing Program");
            System.exit(0);
       }
       inputFile = selecter.getSelectedFile();
       JOptionPane.showMessageDialog(null, "Opening: " + inputFile.getName());
       in = new Scanner(inputFile);
       int[] temps = new int[161];
       int num = in.nextInt();
       int base10 = 0;
       while (in.hasNextInt());
       {
           temps[num]++;
           num = in.nextInt();
       }
       for (int count = 1; count <= 160; count += 10)
       {
           System.out.print(count + " - " + (base10 += 10) + " | " );
           for (int index = count; index <= base10; index++)
           {
               while (temps[index] > 0)
               {
                   System.out.print("*");
                   temps[index]--;
               }
           }
           System.out.println();
       }
       in.close();
    }
}

上面程序的输入样本是什么?第30行是
num=in.nextInt()。最有可能的情况是,文件中有非数字字符。问题是在使用int num=in.nextInt()之前没有签入.hasNextInt();因此,如果输入流中根本没有整数,Java将抛出InputMismatchException。您可以通过在调用.nextInt()之前签入.hasNextInt()来防止这种情况,正如您在代码后面已经做的那样。(基本上与Al1的注释相同)我忘了使用分隔符从输入文件中提取数字。我刚刚添加了它,它使一切正常工作。现在,我的下一个问题是FileNotFoundException,当我选择一个我故意删除的文件,只是为了测试我在“main(String[]args)”之后添加的“throws FileNotFoundException”语句时,它会弹出。我仍在学习这会导致什么,我的印象是它会防止这种异常。您对上述程序的输入示例是什么?第30行是
num=in.nextInt()。最有可能的情况是,文件中有非数字字符。问题是在使用int num=in.nextInt()之前没有签入.hasNextInt();因此,如果输入流中根本没有整数,Java将抛出InputMismatchException。您可以通过在调用.nextInt()之前签入.hasNextInt()来防止这种情况,正如您在代码后面已经做的那样。(基本上与Al1的注释相同)我忘了使用分隔符从输入文件中提取数字。我刚刚添加了它,它使一切正常工作。现在,我的下一个问题是FileNotFoundException,当我选择一个我故意删除的文件,只是为了测试我在“main(String[]args)”之后添加的“throws FileNotFoundException”语句时,它会弹出。我仍在学习这会导致什么,我的印象是这会防止这种异常。
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 CoolWeather.main(CoolWeather.java:30)