For an assignment I have been asked to create a Java program that reads integer values from a file and stores them into an array with a length of 40, and prints the values in reverse order. My problem is that the assignment also requires it to work when there are less than 40 values in the file. This is what I have tried:
import java.io.*;
import java.util.Scanner;
public class Set8_Prog3
{
public static void main (String[] args) throws IOException
{
FileReader i = new FileReader("Set8_Prog3 numbers.txt");
Scanner j = new Scanner(i);
int[] values = new int[40];
int k = 0;
int last = -1;
while (k < 40)
{
values[k] = j.nextInt();
last = values[k];
k++;
}
System.out.println("The values from the file in reverse order is: ");
while (last >= 0)
{
System.out.println(values[last]);
last--;
}
}
}
It compiles successfully, but when I run it I get an error saying java.util.NoSuchElementException. Also, I am not supposed to use an ArrayList.