I'm currently re-working through tasks that I was set at the start of the year and one thing I really didn't grasp the concepts of was loops and reading/writing to/from files. The task in hand is to read in a bunch of salaries from a text file, add them up and calculate an average and then print out the results in console.
So far I have this:
import java.util.*;
import java.io.*;
public class loopingSalaryTotal {
public static void main (String[] args) throws IOException {
int [] salaries = new int[100];
Scanner scan = new Scanner("salaries1.txt");
int index = 0;
while (scan.hasNext()) {
salaries[index]=(scan.nextInt());
index++;
}
for (int i = 0; i < index; i++) {
System.out.println(salaries[i]);
}
scan.close();
}
}
And it's throwing this error message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at loopingSalaryTotal.main(loopingSalaryTotal.java:18)
Also, I fully understand that I'm nowhere near being able to actually add up the numbers then calculate an average, but if anyone could nudge me in the right direction that'd be greatly appreciated.
Here is some example input from input.txt:
17283
12312
12312
12314
43242
64363
12364
74534
If you only want the average, then you don't need to store each salary. Instead, keep a running total before calculating the average at the end:
import java.util.*;
import java.io.*;
public class loopingSalaryTotal {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(new File("salaries1.txt"));
int items = 0;
double total = 0;
while (scan.hasNextInt()) {
// add the next salary to the total
total += scan.nextInt();
// increase the number of encountered salaries by 1
items++;
}
double average = total/items;
System.out.println("average:" + average);
scan.close();
}
}
Your problem is also that you should use Scanner.hasNextInt. This is because Scanner.hasNext may return true even though there are no more integers in your file. For example, if your file were
125
172
199
zalgo_calls_your_name
After reaching 199, Scanner.hasNext would return true. However, there is no integer after 199—just a string. So, when you call Scanner.nextInt in your loop, an exception is thrown since no int can be found.
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