Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
Old Sep 29th, 2007, 3:36 AM   #1
truBlu1
Newbie
 
Join Date: Sep 2007
Posts: 5
Rep Power: 0 truBlu1 is on a distinguished road
code to add numbers in an array

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;
  }
}
truBlu1 is offline   Reply With Quote
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
relation between array and pointer n00b C++ 6 Oct 12th, 2006 3:38 PM
Median/Mode in arrays? {Need help} Java|Tera Java 27 Nov 29th, 2005 10:50 AM
fill array with unique numbers secrecy230 Java 4 Aug 9th, 2005 9:55 PM
random numbers in 2D array cwl157 Java 4 Apr 29th, 2005 6:08 AM
Installing IPB 2.03 bh4575 Other Web Development Languages 0 Apr 23rd, 2005 2:36 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 4:36 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC