-1

I am making a program that runs a formula on the numbers inputted. The first integer in the input describes the amount of lines, or integers to be used in the formula. I am approaching this by calculating the answers and pushing them into an array. However, I am getting an array out of bounds exception in one of my for loops, and I can't figure out why.

Here is my main method:

    public static void main(String[] args) {
    Scanner scan = new Scanner (System.in);
    int[] nums = {};
    int lines = scan.nextInt();
    for(int i = 0; i < lines; i++){
        nums[i] = potFormula(scan.next());
    }
    System.out.println(nums);
}
Steven
  • 19
  • 6
  • 2
    Looks like you need to initialize the nums array to the length of lines – Blue Boy Dec 14 '16 at 21:51
  • As an aside, once you fix the array issue, you'll find that your print statement doesn't do what you want. See http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Sam Dec 14 '16 at 22:05

3 Answers3

4

Arrays have a fixed size that can't be changed once allocated. You're initializing nums to {}, which is an empty array. Its size will always be zero.

Instead, you could use:

int lines = scanner.nextInt();
int[] nums = new int[lines];
Sam
  • 8,330
  • 2
  • 26
  • 51
2

Your array is too small (it has zero elements). Here is one way to fix this:

int lines = scan.nextInt();
int[] nums = new int[lines];

This approach works since you know the size in advance. If you didn't, you could use an ArrayList<Integer>. Array lists have the ability to grow on demand.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You need to initialize the nums array to the length of the lines,

Like this:

public static void main(String[] args) {
    Scanner scan = new Scanner (System.in);
    int lines = scan.nextInt();
    int[] nums = new int[lines];
    for(int i = 0; i < lines; i++){
        nums[i] = potFormula(scan.next());
    }
    System.out.println(nums);
}
Blue Boy
  • 620
  • 1
  • 6
  • 13