0

I am trying to open a file from user input in java and then read that file and grab only the integers in each line then place it into an array and return the array. I'm more familiar with python in grabbing items in a file than java.

Sample contents of the file in one line:

34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 n m ghff

My code:

private static int[] getArray(){
    List<Integer> temp = new ArrayList<Integer>();
    System.out.print("Please input the name of the file to be opened: ");
    try{
        String filename = in.next();
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        while (inputFile.hasNextInt()){
            temp.add(inputFile.nextInt());
        }
    } catch (FileNotFoundException e){
        System.out.println("---File Not Found! Exit program!---");
        System.exit(0);
    }
    int[] array = new int[temp.size()];
    for (int i = 0; i < array.length; i++){
        array[i] = temp.get(i);
    }
    return array;
}

Edit:

I figured it out my while loop was wrong. It should be like this:

while (inputFile.hasNext()){
     if (inputFile.hasNextInt()){
        temp.add(inputFile.nextInt());
     }
     else{
        inputFile.next();
     }
}
Zeke
  • 13
  • 3
  • Does this answer your question? [How to convert List to int\[\] in Java?](https://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java) – Misanty Sep 17 '20 at 01:22
  • that answered one part but I still get a return of 0 as it seems that it doesn't read the file for the integers – Zeke Sep 17 '20 at 01:33

1 Answers1

2

In your case, I wouldn't use Scanner object to get the int values, because when you use scanner, you only get false for hasNext() when you have a EOF(end of file) character. So once you retrieve the filename use the code below, which will eliminate all of the characters from given string and replace it with a single whitespace

String stringWithSingleWS = filename.trim().replaceAll("([a-zA-Z])"," ").replaceAll("\\s{2,}"," ");

Then you can parse it into array and directly return the result without even casting into a List object variable.

    int[] values = java.util.Arrays.stream(stringWithSingleWS.split(" "))
                    .mapToInt(Integer::parseInt)
                    .toArray();
return values;
Misanty
  • 86
  • 10
  • I tried doing that but still get a return of 0. Does it have something to do with my while loop not actually getting integer values? – Zeke Sep 17 '20 at 01:40
  • This is not going to work for the test case `34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 n m ghff` – Spectric Sep 17 '20 at 02:18
  • Check out the answer, I improved it according to your case. – Misanty Sep 17 '20 at 17:24