lkcs26 lkcs26 - 13 days ago 4
Java Question

Trying to make these 2 arrays store the input sum in a 3rd list

I'm studying java, and I'm trying to make this thing work.

I made 3 arrays in java, 2 of which accepts input, with 10 elements each.

The sum of the contents of list1 and list2 should be stored in list 3, and display the results

This is my code (really messy,sorry)

public class List2 {
public static void main(String[]args){
int list1[]=new int[10];
int list2[]=new int[10];
int list3[]=new int[10];
int i, sum=0, num1=0, num2=0;
String input=" ";

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

for(i=0;i<10;i++){
list1[i]=0;
list2[i]=0;
list3[i]=0;
}
for(i=0;i<10;i++){
System.out.print("Input value for list1[" + i + "] = ");

try{
input=in.readLine();
}catch(IOException e){}
num1=Integer.parseInt(input);
list1[i]=num1;
}

for(i=0;i<10;i++){
System.out.println("list[" + i + "] = "+list1[i]);
}
for(i=0;i<10;i++){
System.out.print("Input value for list2[" + i + "] = ");

try{
input=in.readLine();
}catch(IOException e){}
num2=Integer.parseInt(input);
list2[i]=num2;
}
for(i=0;i<10;i++){
System.out.println("list[" + i + "] = "+list2[i]);
}
for(i=0;i<10;i++){
sum = list1[i]+list2[i];
}
for(i=0;i<10;i++){
System.out.println("list3[" + sum + "]="+"list1[" + list1[i] + "]+"+"list2[" + list2[i] + "]");
}
}
}


To my dismay, only the last input of list1 and list2 gets displayed in all of list3. These are the results

**Input value for list1[0] = 1
Input value for list1[1] = 2
Input value for list1[2] = 3
Input value for list1[3] = 4
Input value for list1[4] = 1
Input value for list1[5] = 2
Input value for list1[6] = 3
Input value for list1[7] = 1
Input value for list1[8] = 41
Input value for list1[9] = 2
list[0] = 1
list[1] = 2
list[2] = 3
list[3] = 4
list[4] = 1
list[5] = 2
list[6] = 3
list[7] = 1
list[8] = 41
list[9] = 2
Input value for list2[0] = 4
Input value for list2[1] = 1
Input value for list2[2] = 2
Input value for list2[3] = 1
Input value for list2[4] = 1
Input value for list2[5] = 3
Input value for list2[6] = 1
Input value for list2[7] = 1
Input value for list2[8] = 1
Input value for list2[9] = 1
list[0] = 4
list[1] = 1
list[2] = 2
list[3] = 1
list[4] = 1
list[5] = 3
list[6] = 1
list[7] = 1
list[8] = 1
list[9] = 1
list3[3]=list1[1]+list2[4]
list3[3]=list1[2]+list2[1]
list3[3]=list1[3]+list2[2]
list3[3]=list1[4]+list2[1]
list3[3]=list1[1]+list2[1]
list3[3]=list1[2]+list2[3]
list3[3]=list1[3]+list2[1]
list3[3]=list1[1]+list2[1]
list3[3]=list1[41]+list2[1]
list3[3]=list1[2]+list2[1]


does anybody have an idea what should I do to make it work properly?

Answer

You need to add the values at each index and put them back in the list3.

    for (int i = 0; i < 10; i++) {
        list3[i] = list1[i] + list2[i];
    }