I need to make two int tables that contains four numbers. Numbers can differ. Then I need to compare between the two tables using if and for statements. If either number of the item is greater than the other, then the larger number is added to the sum. Equally large numbers are ignored. The amount should first be set to 100. I tried many ways, but I don't know how to make this comparison! In the code below I added an arraylist. However I think that I should not use it.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
int [] numbers = new int[4];
numbers[0] = 20;
numbers[1] = 10;
numbers[2] = 7;
numbers[3] = 56;
int [] luvut = new int [4];
luvut[0] = 20;
luvut[1] =150;
luvut[2] = 7;
luvut[3] = 37;
ArrayList<Integer> lista = new ArrayList<>();
if ( numbers[0] > luvut[0]) {
lista.add(numbers[0]);
} else if (luvut[0] > numbers[0]){
lista.add(luvut[0]);
} if ( numbers[1] > luvut[1]) {
lista.add(numbers[1]);
} else if (luvut[1] > numbers[1]){
lista.add(luvut[1]);
} if ( numbers[2] > luvut[2]) {
lista.add(numbers[2]);
} else if (luvut[2] > numbers[2]){
lista.add(luvut[2]);
} if ( numbers[3] > luvut[3]) {
lista.add(numbers[3]);
} else if ( luvut[3] > numbers[3]){
lista.add(luvut[3]);
}
System.out.println(lista);
}
}
You could do this without another list, simply add a int variable to hold the initial value and increment it with the appropriate value as you loop through the lists.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
int [] numbers = new int[4];
numbers[0] = 20;
numbers[1] = 10;
numbers[2] = 7;
numbers[3] = 56;
int [] luvut = new int [4];
luvut[0] = 20;
luvut[1] =150;
luvut[2] = 7;
luvut[3] = 37;
int sum = 100;
int numAdd;
for(int i=0; i<luvut.length; i++)
{
numAdd = 0;
if (numbers[i]> luvut[i])
{
numAdd = numbers[i];
} else if (numbers[i] < luvut[i]) {
numAdd = luvut[i];
}
sum+=numAdd;
}
System.out.println(sum);
}
}