Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The Two-sum program in java script runs even when the if statement is false. When I enter a series of number in textbox1, and one number in textbox2. It should display 2 numbers from textbox1 which equals to textbox2.

For eg 1,2,3,6 in textbox1.

5 in textbox2.

The answer should be 2,3.

JavaScript
function TwoSum() {
    inputArray1 = document.getElementById("inputText1").value.split(",");
    inputArray2 = document.getElementById("inputText2").value.split(",");

    var two = [];
    var sum = 0;
    var y = 0;
    y = inputArray2[0];
    var z = 0; 
    var a = 0; //input array 1
    var b = 0; //input array 2

    for (i = 0; i < inputArray1.length - 1; i++) {
        if (z == 0) {
            for (j = inputArray1.length - 1; j >= i; j--) {
                //if (inputArray1[i] + inputArray1[j] == y)
                a = inputArray1[i];
                b = inputArray1[j];

                if (a + b == y)
                {

                    two[sum] = inputArray1[i];
                    sum++;
                    two[sum] = inputArray1[j];
                    sum++;
                    z++;
                    break;
                }
            }
        }
        if (z > 0)
            break;
        else
            var incorrect = false;
    }

    if (z > 0)
        document.getElementById("result").value = two.join(",");
    else
        document.getElementById("result").value = incorrect;
}


What I have tried:

When I enter 2,4,5,3 in 1 textBox and 5 in 2nd textbox, the answer should print 2,3 in the first loop itself. But when I debug, the if(a+b==y) isn't getting executed. It reads as false no matter what and jumps back to a=inputArray1[i], b= inputArray2[i].
Posted
Updated 19-Nov-20 0:29am
v2
Comments
Mehdi Gholam 7-Oct-18 9:43am    
Try : if (a + b === y)
VaiShankar 7-Oct-18 9:52am    
Nope. Still doesn't work :(

1 solution

Because all your numbers are in character string format. So 2 + 3 is actually evaluated as the string 23, not the arithmetic sum 5. You first need to convert your characters into actual numeric values. See JavaScript parseInt() Function[^].
 
Share this answer
 
Comments
VaiShankar 7-Oct-18 11:32am    
Thank you so much. I got the output :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900