我从一个看起来像这样的文件中读到了一个问题:
1 7 21 16 44
2 7 21 16 45
3 7 21 16 46
4 7 21 16 47
5 7 21 16 48
6 7 21 16 49
7 7 21 16 50
我需要将每个数字设置为我的程序中的特定变量,然后继续扫描365次。每行代表(日出日出时的日出日落时分,日落时分)。我正在尝试读取和设置这些变量,以便我可以执行计算。我收到以下错误:
Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
这是我到目前为止的代码:
public void graph(Graphics page)
{
int y = 0; //y-coordinate
int sunriseX = 101;
int sunsetX = 101;
Scanner inputStream = null;
try
{
inputStream = new Scanner("sunData.txt");
}
catch(Exception e)
{
System.out.println("File not found");
System.out.println("or could not be opened.");
}
for (int i = 365; i <= 365; i++)
{
int day = inputStream.nextInt();
setSunriseHour(inputStream.nextInt());
setSunriseMin(inputStream.nextInt());
setSunsetHour(inputStream.nextInt());
setSunsetHour(inputStream.nextInt());
inputStream.next();
switch(sunriseHour)
{
case 4:
y = 120;
break;
case 5:
y = 180;
break;
case 6:
y = 240;
break;
case 7:
y = 300;
break;
case 8:
y = 360;
break;
default:
System.out.println("invalid time");
break;
}
sunrisePoint = y + sunriseMin;
page.drawOval (sunriseX, sunsetHour, 2, 2); // circle
sunriseX += 2;
switch (sunsetHour)
{
case 16:
y = 420;
break;
case 17:
y = 480;
break;
case 18:
y = 540;
break;
case 19:
y = 600;
break;
case 20:
y = 660;
break;
default:
System.out.println("invalid time");
break;
}
sunsetHour = y + sunsetMin;
page.drawOval (sunsetX, sunsetHour, 2, 2); // circle
sunsetX += 2;
} //ends for loop
答案 0 :(得分:2)
在获得之前,请务必检查下一个项目。
while (inputStream.hasNext()) {
int day = inputStream.nextInt();
setSunriseHour(inputStream.nextInt());
setSunriseMin(inputStream.nextInt());
setSunsetHour(inputStream.nextInt());
setSunsetHour(inputStream.nextInt());
....
}
您还可以查找Scanner类的其他方法,这些方法更具体于值类型,例如Scanner#hasNextInt()
while (inputStream.hasNextInt()) {
int day = inputStream.nextInt();
...
}
答案 1 :(得分:-1)
尝试使用:
try
{
Scanner inputStream = new Scanner("sunData.txt");
}
而不是:
Scanner inputStream = null;
try
{
inputStream = new Scanner("sunData.txt");
}