How to exit the loop and print a statement when the sum of two integers in an array is not equal to zero

Rahul :

Am trying to store and print an array whose sum of two integers in the given array is equal to zero. But when there are no two integers whose sum is equal to zero, am unable to exit the loop and print "There are no two integers whose sum is zero" . Please let me know how to solve this.

public static void main(String[] args) {
        int[] origArr = { 1, 2, 3, -6, 8, 4 };
        for (int i = 0; i < origArr.length; i++) {
            int firstNumber = origArr[i];
            for (int j = i + 1; j < origArr.length; j++) {
                int secondNumber = origArr[j];
                if (firstNumber + secondNumber == 0) {
                    int[] newArr = new int[2];
                    newArr[0] = firstNumber;
                    newArr[1] = secondNumber;
                    System.out.println(Arrays.toString(newArr));

                }

                else {

                    System.out.println("There are no two integers whose sum is zero ");

                }

            }

        }

    }

when the 'If' condition is not satisfied, system is printing the sopln multiple times as long as the loop is iterating.

jhamon :

If there are no couple of integers matching your condition, that means you have already check all the possible combinations in your array.

If you have check all the combinations, that means both loops are terminated.

The "no solution" print should be done after the two loops. To know if you need to print it or not, you can use a boolean. Setting it to true when any matching combination is found:

public static void main(String[] args) {
    int[] origArr = { 1, 2, 3, -6, 8, 4 };
    boolean solutionFound = false;
    for (int i = 0; i < origArr.length-1; i++) {
        int firstNumber = origArr[i];
        for (int j = i + 1; j < origArr.length; j++) {
            int secondNumber = origArr[j];
            if (firstNumber + secondNumber == 0) {
                // set the flag to true
                solutionFound = true;
                System.out.println(firstNumber + ", " + secondNumber);
            }
        }
    }
    // check the flag to see if a solution was found
    if (!solutionFound) {
        System.out.println("There are no two integers whose sum is zero ");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27005&siteId=1