Can &#214;zkan - 1 year ago 86
Java Question

# java array to find the small number

``````import java.util.Scanner;

public class App {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int x = sc.nextInt();

int[][] numberPair = new int [2][x];

for(int i=0; i<x; i++){
for(int k=0; k<2; k++){

numberPair[k][i] = sc.nextInt();
}
}

int[] solution = new int[x];

for(int i=0; i<x; i++){

if(numberPair[0][i]<numberPair[1][i]){
//a minimum
solution[i] = numberPair[0][i];
}
else {
//b min
solution[i] = numberPair[1][i];
}
for(i=0; i<x; i++)
System.out.printf(solution[i] + " ");

}
}
}
``````

Java newb here! This is a basic exercise for choosing the small number between two numbers in a given list and printing them out. It always gives the correct answer for the first one but 0 for the following. I couldn't figure out why, any help or tip will be appreciated thanks :)

Answer Source

Same variable i was used for both cycles. This code will work fine:

``````for(int i=0; i<x; i++){

if(numberPair[0][i]<numberPair[1][i]){
//a minimum
solution[i] = numberPair[0][i];
}
else {
//b min
solution[i] = numberPair[1][i];
}

}

//this part was inside calculating loop
for(int j=0; j<x; j++)
System.out.printf(solution[i] + " ");
``````

Use different variables for different iterations to prevent such errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download