简体   繁体   中英

How can I pair my user's input number in an array whose sum is equal to specified input number?

Here's my hard work code so far, we were asked to do it with GUI. Please help me on what approach should I do next to pair my user's input number in an array whose sum is equal to specified input number?

package josh;


import javax.swing.JOptionPane;

public class Sample {


    public static void main (String args[]) {

        int colInput,rowInput;


        String user_col = JOptionPane.showInputDialog("Enter Column Of Array:");
        colInput =  Integer.parseInt(user_col);


        String user_row = JOptionPane.showInputDialog("Enter Row Of Array:");
        rowInput = Integer.parseInt(user_row);



        int user_value;


        for (int i = 0; i < colInput; i++) {
            for (int j= 0; j < rowInput; j++) {

            String values = JOptionPane.showInputDialog(null, "Enter Value "+(i+1));
             user_value = Integer.parseInt(values);

            final Integer [] value_arr = new Integer [user_value];




                }

            }


        }
}

Here's the sample input and output

这是示例输入和输出

I would give you the basic logic that you can use.

// value_arr[] is the array where you have all the elements.
// sum is the number to be paired

Arrays.sort(value_arr);
int i=0,j=value_arr.length-1;

// now value_arr is sorted. we'll use two pointers i & j to move.. i moves in from left side towards centre and j moves from right side towards centre

while(i<j){
     if(value_arr[i]+value_arr[j]>sum){
         j--;
     }
     else if(value_arr[i]+value_arr[j]<sum){
         i++;
     }
     else if(value_arr[i]+value_arr[j]==sum){
         System.out.println(value_arr[i]+"+"+value_arr[j]+"="+sum);
     }
}

Let me know if it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM