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();
}
}