我正在编写一个程序,它接受文件的输入并打印城市及其降雨量的列表。我在使用扫描仪来确定所需阵列的长度和城市的降雨数据时遇到了麻烦。
我不断收到此异常
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.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at BarChart.main(BarChart.java: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);
}
}
}
最佳答案
在您的文件中,如果列表的大小是第一行的唯一内容,换句话说,如下所示:
2
London
Paris
1
2
然后,当您进入 for 循环读取城市名称时,扫描仪尚未读取第一个换行符。在上面的示例中,对 newLine()
的调用将读取空行和 London
,而不是 London
和 Paris
>.
因此,当您进入第二个 for 循环读取降雨数据时,扫描仪尚未读取最后一个城市(上例中的 Paris
),并且会抛出InputMismatchException
因为城市名称显然不是有效的 int
。
关于java - 扫描仪异常 : java. util.InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19460363/