这是一些类(class)作业的一部分,我宁愿自己弄清楚,所以如果可能的话,请不要直接给出答案,而是指出正确的方向或告诉我错误在哪里。
我必须创建一些代码来从文件中读取文本,然后用它做一些其他事情,我的问题是在读取第三个文本 block 后我的 for 循环失败了。
这是我必须阅读的文字
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
Unit Five
4
32 6.5
32 8
32 7
32 8
...
这是第 9 单元
它是一个 .txt 文件,与我的代码位于同一目录中。 这是我的代码。
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import java.util.*
;
public class stringvariable {
public static void main(String[] args) throws FileNotFoundException
{
String shop; //shop unit
int num; // number of sales assistants
int num2 = 9; // number of units
int hour; //hours worked
int rate; // rate of pay
int total = 0; // total cost
int i = 0;
int sum;
Scanner inFile = new Scanner (new FileReader ("4001Comp-CW1-TASK3-Infile.txt")); //opens the CW1-task3-Infile file
for (int b = 0; b <num2; b++)// for loop to read through all 9 shop units
{
shop = inFile.nextLine();
num = inFile.nextInt();
for (i = 0; i <num; i++)// for loop repeats as many times as there are staff.
{hour = inFile.nextInt();
rate = inFile.nextInt();
total += (rate*hour);
System.out.println(total);}
System.out.println(shop +"s total cost is "+ total);
shop = inFile.nextLine();
shop = inFile.nextLine();
num = 0;
hour= 0;
rate = 0;
total = 0; }
}
}
在“第 4 单元”之前,我的打印输出正是我所需要的
256
484
712
824
Unit Ones total cost is 824
Unit Twos total cost is 0
252
504
Unit Threes total cost is 504
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 stringvariable.main(stringvariable.java:28)
最佳答案
第 4 单元似乎包含 float ,您正在使用 nextInt()
读取它,因此异常。
您可以使用 hasNextInt()
和 hasNextDouble()
方法来优雅地处理这个问题:)
关于Java - For 循环将无法完成,仅三个循环后就会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20199471/