# Find values that add up to a number

## Input

The input for this problem is a String of sorted numbers and a special number. The syntax of the input would be 1,2,3,4;5

## Output

The program will output all of the possible sums that equate to the special number. The output for the example would be 1,4;2,3

I solved the problem by using some simple subtraction. The program will begin at the greatest value and work its way to the lowest value. For each value the program will subtract it from the pre-set value and search the array for that value. I want to know what I could do better for this.

import java.util.*;
public class NumPairs {
static String line = "1,2,3,4;5";
public static void main(String[] args) {
String fina = "";
if(!line.equals("")){
String a = line.substring(line.indexOf(";")+1,line.length());
String[] valu = line.substring(0,line.indexOf(";")).split(",");
for(int h = valu.length-1; h >0; h--){
int need = Integer.parseInt(a) - Integer.parseInt(valu[h]);;
if(Arrays.asList(valu).indexOf(need + "") != -1 && fina.indexOf(need +"") == -1 && need != Integer.parseInt(valu[h])){
if(need > Integer.parseInt(valu[h]))
fina += valu[h] +","+need +";";
else
fina += need +","+ valu[h] + ";";
}
}
}
if(fina.equals(""))
System.out.println("NULL");
else
System.out.println(fina.substring(0,fina.length()-1));
}
}

• Welcome to Code Review! I hope you get some great answers. – Phrancis Feb 26 '16 at 20:41
• – h.j.k. Feb 27 '16 at 2:35

## 1 Answer

### Lack of separation of concerns

You have a single main function that:

1. Reads a String and parses it to an internal format
2. Applies logic to it (finds numbers that sum to the target)
3. Pretty prints the result

You should have at least 3 more functions:

public class NumPairs {

// Pseudocode, to return two objects at once read
// http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method
public static (int[], int) parseInput(String input) {

}

public static int[][] sumsTo(int[] list, int result) {

}

public static String prettify(int[][] result) {

}

public static void main(String[] args) {
// Simply use the other functions
}

}


You may still need to subdivide sumsTo surther.

• Surely you mean "prettify" – shmosel Mar 1 '16 at 22:41