Mark Nelson
Mark Nelson

Reputation: 11

Java Array Integer manipulation

Cant seem to figure out why my array isnt outputting the correct value. The sum prints out as the first integer in the array. I wanted the sum of all the integers in the array. Any ideas what could be wrong? I attempted to convert the int to a string to be sent out.

  //Add values of Integers
  int i; int sum = 0; 
  for(i = 0; i < intarray.length; i++){  
      sum = sum + intarray[i];
  }

  String sumOut =  Integer.toString(sum);
  System.out.println( "to Client: " + sumOut);
  toclient.writeBytes("Sum = " +sumOut+'\n');

Upvotes: 1

Views: 1581

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83567

Your code looks correct. Try printing out the contents of intarray to be sure what it contains. Also, how do you put values into intarray. Post some code to show us. Perhaps the array is not populated correctly.

Also, there is no need for the line

String sumOut =  Integer.toString(sum);

Java will convert an int to a String automatically when you use the + operator, for example:

System.out.println("to Client:" + sum);

Upvotes: 2

duffymo
duffymo

Reputation: 308988

Here's how I'd do it:

package cruft;

/**
 * IntegerSum description here
 * @author Michael
 * @link
 * @since 7/25/12 8:14 PM
 */
public class IntegerSum {
    public static void main(String[] args) {
        int [] values = new int[args.length];
        for (int i = 0; i < args.length; ++i) {
            values[i] = Integer.valueOf(args[i]);
        }
        System.out.println(String.format("sum = %d", sum(values)));
    }

    public static int sum(int [] values) {
        int sum = 0;
        for (int value : values) {
            sum += value;
        }
        return sum;
    }
}

Upvotes: 2

Related Questions