I've been having stressful issues all day on this program to read a text file for integers and storing the integers into an array. I thought I finally got the solution with the code below.
But unfortunately.. I have to loop through the file with the method hasNextLine(). Then using nextInt() to read integers from the file and store them into an array. So using scanner constructor, hasNextLine(), next(), and nextInt() methods.
Then use try and catch to determine which words are integers and which are not by using the InputMismatchException. Also a exception for blank lines in the file? Problem is I did not use a try and catch and exceptions, as I just skipped over none-ints. Also, I'm using a int array so I want to do this without list.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.println(array[v]);
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//print number of integers
//print all integers that are stored in array
}
}
Then I'll be printing everything in my 2nd method, but that I can worry about later. :o
Example Content of Text File:
Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1
Sample Output Goal:
number of integers in file "groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
Sorry for the similar question. I'm very stressed out, and even more that I was doing it all wrong... I'm completely stuck at this point :(
printfat the end.Listimplementation (ArrayListfor example ): that way you are not obliged to declare its size at the beginning and you don't have to manage the index of the items you put in it.