如何在java中使用scanner读取.txt文件时删除inputMismatchException

时间:2016-05-19 08:13:44

标签: java

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

public class FrequencyCount
{
    public static void main(String...args) throws IOException
    {
        int count0=0;
        int count1=0;
        int x=0;
        //System.out.println(new File(".").getCanonicalPath());
        Scanner scan=new Scanner(new File("F:\\DUCAT COCHNG\\java progs\\IO\\str.txt.txt"));
        while(scan.hasNext())
        {
            x=scan.nextInt();
            if(x==0)
                count0++;
            else if(x==1)
                count1++;
        }   

        System.out.println("Frequency of 0's is: "+count0);
        System.out.println("Frequency of 1's is: "+count1);

    }
}

显示的输出是:

  

F:\ DUCAT COCHNG \ java progs \ IO> java FrequencyCount线程异常   “main”java.util.InputMismatchException:对于输入字符串:“   00000111010010011001010010100101010001000101110111110101010011101001001010010010   1"           at java.util.Scanner.nextInt(Scanner.java:2165)           在java.util.Scanner.nextInt(Scanner.java:2118)           在FrequencyCount.main(FrequencyCount.java:15)

     

F:\ DUCAT COCHNG \ java progs \ IO>

str.txt文件是:

  

000001110100100110010100101001010100010001011101111101010100111010010010100100101

2 个答案:

答案 0 :(得分:0)

我认为这可能有所帮助:

try{
        Scanner scan = new Scanner(new File(filename));
        while (scan.hasNext())
        {
           String str = scan.next(); 
            char[] myChar = str.toCharArray();
            for(char c: myChar){
                x=Character.getNumericValue(c);
                if(x==0) 
                    count0++; 
                else if(x==1) 
                    count1++; 
            }
        }
       System.out.println("Frequency of 0's is: "+count0);
       System.out.println("Frequency of 1's is: "+count1);
   }
  catch(Exception e)
  { e.printStackTrace();}

答案 1 :(得分:0)

您想使用scan.hasNextInt()代替scan.hasNext()。后者检查任何令牌,我怀疑你的文件末尾有一行扫描器正在解析。这显然无法转换为整数,因此抛出异常。

您可能还想关闭scanner。只需使用scan.close()即可。在这么小的计划中,这里并不是绝对必要,而是良好的实践。