this is part of some coursework which I would rather figure out for myself so if possible could you please not give the answer right out but point me in the right direction or tell me where my error is.
I have to create some code that will read text from a file and then do some other things with it, my problem is after reading the third block of text my for loop fails.
here is the text i have to read
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
...
This goes up to unit 9
it is a .txt file in the same directory as my code. here is my code.
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; }
}
}
my printouts are exactly what I need up until 'unit 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)
Unit 4 seems to contain floating point numbers, which you are reading with nextInt()
, hence the exception .
You can use the hasNextInt()
and hasNextDouble()
methods to handle this gracefully :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With