這是我想爲自己弄明白的一些課程作品的一部分,所以如果可能的話,請不要直接給出答案,而是指出正確的方向或告訴我我的錯誤在哪裏。Java - For Loop不會完成,僅在三個週期後崩潰
我必須創建一些代碼來讀取文件中的文本,然後用它做一些其他的事情,我的問題是在讀取第三個文本塊之後我的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)
6.5不是INT。 – Hellion
我敢打賭,你正試圖讀取一個小數值(6.5)並將其存儲到一個整數變量(int rate;)中。 – OnoSendai