I'm working on an assignment which is to read in only integers from a text file (that contains strings and doubles as well) and put them into an array, sort that array, then print each element within it.
I'm getting a NoSuchElementException in my console here's a screenshot NoSuchElementException
I believe the issue comes from fileInput.next(); in my while loop maybe because I've reached the end of the .txt file but I'm not sure how to fix this - any help is much appreciated.
Also here's the .txt file .txt file along w/ my code below:
package Main;
import java.io.*;
import java.util.*;
public class FilterSort {
public static int[] doubleArrayAndCopy(int[] arr) {
//use the length method to get the size of arr
int SIZE = arr.length;
//create a temp array that is double the size of arr
int [] tempArr = new int[2*SIZE];
//store the elements of the arr into temp array using for-loop
for (int i = 0; i < SIZE; i++){
tempArr[i] = arr[i];
}
return tempArr;
// return the temp array
}
public static void main(String[] args){
int[] data = new int[8];
int index = 0;
try {
// create a Scanner and open a file called "data.txt"
//initialize index = 0
Scanner fileInput = new Scanner(new File("src/main/data.txt"));
// while there are lines in the file
// read the line from the file (get tokens)
// check if the token is integer or not.
while (fileInput.hasNextLine()) {
if(fileInput.hasNextInt()){
data[index] = fileInput.nextInt();
index++;
}
else{
fileInput.next();
}
if (index >= data.length){
data = doubleArrayAndCopy(data);
}
}
/* A note : For checking integers : You can use hasNextInt() method of Scanner. If it will be Integer(true), then you can use that token by using nextInt() method of Scanner to read it, if false, then use next() method of Scanner and throw away this token*/
// store the integer token into the answers array
// increment the index
// use the length method of arrays to check if the index is equal or greater
// than the length of array, if it is true, call here doubleArrayAndCopy.
if(index==0){
System.out.println("There is no data in file");
}
else
{
// Sort the array
Arrays.sort(data);
System.out.println("Elements of array sorted in ascending order: ");
// and Print the elements using loop
for (int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
catch(FileNotFoundException e){
System.out.println("Error: Data file not found");
}
}
}
I've tried catching the error and throwing it but that doesn't seem to solve the problem, to be honest I'm lost on what else to do.