1
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 :)

3
  • the small number between two numbers in a given list ... can you give us an example of what you mean exactly? Commented Aug 29, 2016 at 14:44
  • Sample inputs and expected outputs would be helpful. Commented Aug 29, 2016 at 14:51
  • For example if first input is 3, then 3 pairs of numbers should be entered and it will print the small numbers in pairs. Let's say: 3 23 34 12 3 14 354 It will print 23 3 14. I accidentally put last for statement into the previous one, that was what caused the error. Thanks everyone! Commented Aug 29, 2016 at 15:11

2 Answers 2

1

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.println(solution[i] + " ");

Use different variables for different iterations to prevent such errors.

Sign up to request clarification or add additional context in comments.

1 Comment

System.out.println(solution[j] + " "); Little correction. :)
1

The problem is that your ouput is inside the loop where you fill your array.

Change your code to this:

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(int i=0; i<x; i++) {
    System.out.printf(solution[i] + " ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.