Java - For 循环将无法完成,仅三个循环后就会崩溃

标签 java loops for-loop

这是一些类(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/

相关文章:

javascript - 为什么 addEventListener 在事件发生之前触发?

java - 在 Java 中查找简单序列重复的有效方法

java - 无法在 "/usr"找到 $JAVA_HOME,继续使用系统提供的 Java

javascript - 为什么这些嵌套的 forEach 循环会这样?

c++ - 从 char 数组中删除条目

javascript - 循环遍历数组并过滤电子邮件

c# - 什么是 C# Regex 相当于 Java 的 appendReplacement 和 appendTail

java - Nashorn JavaScript Invocable.getInterface 在 Web 应用程序中跨类加载器失败

arrays - 使用 bash/expect 中的变量索引到数组中

php - 加快循环内的查询速度?