This program should be simple. I think, however, I'm misunderstanding how Java handles arrays. This code compiles fine but when my for loop tries to access the elements I get an out of bounds error. My only guess is that I've either declared my array wrong or I've misunderstood how Java handles passing by reference. Please help me.
For reference, the output is supposed to look similar to:
Input: 1, 2, 3, 4
Ouput: 1+4=5, 2+3=5
//Lab6: Using void methods and 1D arrays to print the sum of numbers in an array (1st + nth, 2nd + nth-1, etc.)
//Input: A bunch of numbers
//Output: A bunch of sums
//Filename: Lab6.java
import java.util.*;
public class Lab6
{
public static void main(String [] args)
{
System.out.println("How many numbers will be input?");
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
int [] numbers = new int[n];
getNumbers(numbers);
for(int i = 0; i < n/2; i++)
System.out.println(numbers[i] + " + " + numbers[n-i] + " = "
+ numbers[i]+numbers[(n-1)-i]);
if(n % 2 != 0)
System.out.println(numbers[n/2+1] + " could not be added to anything.");
}
static void getNumbers(int [] numbers)
{
System.out.println("Please enter the numbers.");
Scanner keyboard = new Scanner(System.in);
for(int i = 0; i < numbers.length; i++)
numbers[i] = keyboard.nextInt();
return;
}
}