I am trying to do a lab where I am supposed to find the mode from a numbers.txt file. But I'm having problems storing the numbers in an array. I understand how to read the file but for some reason when I am trying to store the numbers I get a java.util.NoSuchElementException. I think that means the scanner I am using doesn't have anything else to read off of but I put the method in a try-catch already so I don't understand what's going on.
Here's the main part of the problem:
int [] modeArray = new int [total];
try {
in = new Scanner(new File("numbers.txt"));
for (int x = 0; x <= total; x++) {
modeArray[x] = in.nextInt();
}
}
catch (IOException i) {
System.out.println("Error: " + i.getMessage());
}
And here's the rest of the code if you want to see the rest of the lab:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
/**
* lab 16.1
*
* @author (Raymond Ma)
* @version (1/3/15)
*/
public class firstLab {
public static void statistics() {
Scanner in;
Scanner inTwo;
Scanner inThree;
int total = 0;
double numbers = 0;
double num = 0;
double standardDeviation;
//Average part
try {
in = new Scanner(new File("numbers.txt"));
while (in.hasNextInt()) {
total += in.nextDouble();
numbers++;
}
}
catch (IOException i) {
System.out.println("Error: " + i.getMessage());
}
System.out.println("The Average of this huge list of integers is " + total/numbers);
//Standard deviation part
try {
inTwo = new Scanner(new File("numbers.txt"));
while (inTwo.hasNextInt()) {
num = Math.pow((inTwo.nextDouble() - (total/numbers)),2);
}
}
catch (IOException i) {
System.out.println("Error: " + i.getMessage());
}
standardDeviation = Math.sqrt(num/(numbers-1));
System.out.println("The Standard Deviation of this huge list of integers is " + standardDeviation);
//This is the most annoying part (the mode)
int [] modeArray = new int [total];
try {
inThree = new Scanner(new File("numbers.txt"));
for (int x = 0; x <= total; x++) {
modeArray[x] = inThree.nextInt();
}
}
catch(IOException i) {
System.out.println("Error: " + i.getMessage());
}
System.out.println("The Mode of this huge list of integers is ");// + )
}
}
while (in.hasNext()) {...}instead of a for loop, even if you know how many numbers you're reading. What line causes the problem?