d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Whats Wrong With My Code? > Java
Add Reply New Topic New Poll
Member
Posts: 3,710
Joined: May 5 2008
Gold: 165.52
Nov 20 2012 02:19pm
import java.util.Scanner;
import java.io.*;
public class SumOfElements
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);

int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;

int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{

int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;

}

else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}

}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{

evenSum =evenData[evenIndex] + evenSum;

}
System.out.print("Sum of even elements: " + evenSum);

for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{

oddSum = oddData[oddIndex] + oddSum;

}
System.out.print("Sum of odd elements: " + evenSum);

for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);

}//end main
}//end class


When i run it, it will print the sum of even numbers correctly, but the same value will occur for oddSum and the value "0" will occur for sum of all....

Would be nice if someone could tell me where i've gone wrong :)
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Nov 20 2012 05:28pm
Code
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;


Pay very close attention to what's happening here. Get out some paper and pencil if you need to.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll