2013-10-18 76 views
1

我正在編寫一個程序,接受來自文件的輸入並打印城市及其降雨的列表。我在確定陣列長度的掃描儀以及城市的降雨量數據方面遇到了問題。掃描儀異常:java.util.InputMismatchException

我不斷收到此異常線程 「主要」 java.util.InputMismatchException

異常在java.util.Scanner.throwFor(Scanner.java:909) 在java.util.Scanner中。在BarChart.main上的java.util.Scanner.nextInt(Scanner.java:2119) (BarChart.java:下一個(Scanner.java:1530) (java.util.Scanner.nextInt(Scanner.java:2160) 29)

這是我的代碼:

import java.util.Scanner; 

public class BarChart 
{ 
    public static void main (String[] args) 
    { 
     //create scanner 
     Scanner scan = new Scanner(System.in); 

     //create size variable 
     int size = scan.nextInt(); 

     //create arrays to hold cities and values 
     String[] cities = new String [size]; 
     int[] values = new int [size]; 

     //input must be correct 
     if (size > 0) 
     { 
      //set values of cities 
      for(int i=0; i<size; i++) 
      { 
       cities[i] = scan.nextLine(); 
      } 

      //set values of the data 
      for(int j=0; j<size; j++) 
      { 
       values[j] = scan.nextInt(); 
      } 

      //call the method to print the data 
      printChart(cities, values); 
     } 
     //if wrong input given, explain and quit 
     else 
     { 
      explanation(); 
      System.exit(0); 
     } 
    } 

    //explanation of use 
    public static void explanation() 
    { 
     System.out.println(""); 
     System.out.println("Error:"); 
     System.out.println("Input must be given from a file."); 
     System.out.println("Must contain a list of cities and rainfall data"); 
     System.out.println("There must be at least 1 city for the program to run"); 
     System.out.println(""); 
     System.out.println("Example: java BarChart < input.txt"); 
     System.out.println(""); 
    } 

    //print arrays created from file 
    public static void printChart(String[] cities, int[] values) 
    { 
     for(int i=0; i<cities.length; i++) 
     { 
      System.out.printf("%15s %-15s %n", cities, values); 
     } 
    } 
} 
+0

參見http://stackoverflow.com/questions/19460288/java-util-inputmismatchexception-error-when-scanning-from-a-txt -文件 –

回答

2

在您的文件,如果列表的大小是在第一行的唯一的事,換句話說,就像這樣:

2 
London 
Paris 
1 
2 

那麼當你進入for循環讀取這個城市的名字,Scanner還沒有讀過第一個換行符。在上面的示例中,對newLine()的調用將讀取一個空行和London,而不是LondonParis

因此,當你到了第二個for循環中雨量數據讀取,該掃描儀還沒有在最後一個城市讀(在上面的例子Paris)着呢,將引發InputMismatchException以來,我市的名字是顯然不是有效的int

0

根據錯誤消息以及出現錯誤的位置,很可能您嘗試讀取整數,但您正在讀取的實際數據不是數字。

您可以通過將scan.nextInt()更改爲scan.next()並打印出您實際獲得的值來驗證此情況。或者,你可以添加的形式是「錯誤處理」:

 for(int j=0; j<size; j++) 
     { 
      if (scan.hasNextInt() 
      values[j] = scan.nextInt(); 
      else 
      throw new RuntimeException("Unexpected token, wanted a number, but got: " + scan.next()); 
     }