0

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Evan
  • 11
  • 3
  • *"I believe the issue comes from fileInput.next();"* -- Did you get a stack trace? It should have numbers that match lines in source code. Find a line in the stack trace that points to a method in *your* source code, and check the line number. https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors . If you do find the line of code, it would help to edit the question to highlight it: `// **** Following line throws NoSuchElementException *******` – Old Dog Programmer Feb 13 '23 at 02:35
  • Yes, I did. It points to line 51 of my code which reads fileInput.next(); and I'm stumped on what to do to fix it. Here's a screenshot: https://imgur.com/a/aqQ7nIm – Evan Feb 13 '23 at 02:40
  • I also updated my post to include the exact error I'm seeing via the Stack Trace. – Evan Feb 13 '23 at 02:43
  • What if you were to change `while (fileInput.hasNextLine()) ` to `while (fileInput.hasNext())` ? – Old Dog Programmer Feb 13 '23 at 02:49

1 Answers1

0

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 solved this program in a different way, where I read all the lines in the text file and try to parse each element (separated by space) into integer.


import java.io.*;
import java.util.*;

public class FilterSort {

    public static void main(String[] args) {
        int[] data = new int[100];
        int index = 0;
        try {
            // create a Scanner and open a file called "data.txt"
            //initialize index = 0

            Scanner fileInput = new Scanner(new File("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()) {

                String temporary = fileInput.nextLine();
                // split the entire line using space delimiter 
                String[] temporary_array = temporary.split(" ");
                for (String s : temporary_array) {
                    // Use Integer.parseInt to parse an integer
                    try {
                        int number = Integer.parseInt(s);
                        data[index] = number;
                        index++;
                    } catch (NumberFormatException e) {
                        // This is not an integer, do nothing
                    }
                }
            }

            if (index == 0) {
                System.out.println("There is no data in file");
            } else {
                // Copy the number out from the data array to output array
                int[] output = new int[index];
                System.arraycopy(data, 0, output, 0, index);
                // Sort the output array
                Arrays.sort(output);
                System.out.println("Elements of array sorted in ascending order: ");
                // and Print the elements using loop 
                for (int i = 0; i < index; i++) {
                    System.out.println(output[i]);
                }
            }

        } catch (FileNotFoundException e) {
            System.out.println("Error: Data file not found");
        }

    }

}

Output using your text file:

Elements of array sorted in ascending order: 
-8
-3
0
1
1
2
2
3
3
4
4
4
9
22
44
90
92
98
99
99
99
100
162

However, this solution has its own limitation (i.e. When the number of integer is greater than 100 or unknown), but can be solved using more sophisticated technique (i.e. ArrayList).

Good luck in your assignment.

Cheng
  • 1
  • 1