user3247346
user3247346

Reputation: 13

i cannot convert this java code to javascript

this a program that work based on a specific algorithm. it works perfectly in java but whenever I run the html code i dont get error but it show me only the first three number while in java code the for loop continues until to show the whole numbers

Java code

 package test1;

  public class Test1
  {
  public static void main(String arg[])
   {
    int num = 1;
    counterA(num);
  }

  public static void counterA(int num)
   {       
     for (int i = num; i <= 24; i += 5)
     {
        System.out.println(i);
        counterB(i);
     }
 }

 public static void counterB(int i)
 {
    counterA(i * 3);
 }

}

HTML code

<script>

    var num1 ;
    counterA(num1);
    var total=0;
    var counterA=function(num11)
    {
        for (num1 = num11; num1 <= 24; num1 += 5)
        {
            console.log(num1);
            counterB(num1);
        }

    }

    var counterB =function (num11)
    {
        counterA(num11 * 3);
    }
 </script>

 <body>

<button onclick="counterA(1)">Try it</button>

 </body>

</html>

Upvotes: 0

Views: 97

Answers (3)

Techmiya
Techmiya

Reputation: 53

You can do

<html>
<script type="text/javascript">
    function counterA(num11){
        for (var num1 = num11; num1 <= 24; num1 += 5) {
            alert(num1);
            counterA(num1*3);
        }
    }
</script>

<body>
    <button onclick="counterA(1)">Try me</button>
</body>

</html>

Upvotes: 0

GuyT
GuyT

Reputation: 4416

You've a few mistakes in your code:

  1. You're calling a function before it is defined. Calling counterA before it's defined.
  2. You've to reset the counter num1 in the for loop

Possible option to make your code to work:

  1. Remove var num1 ; counterA(num1); var total=0;
  2. Replace for (num1 = num11; ... with for(var num1 = num11; ...

Upvotes: 1

Atul O Holic
Atul O Holic

Reputation: 6792

Try this,

<!DOCTYPE html>
<html>

<script>

function counterA(num11)
{
   var num1;
    for (num1 = num11; num1 <= 24; num1 += 5)
    {
        alert(num1);
        counterB(num1);
    }
}

function counterB(num11)
{
    counterA(num11 * 3);
}
</script>

<body>

<button onclick="counterA(1)">Try it</button>

</body>

</html>

This is giving me output as 1, 3, 9, 14, 19, 24, 8, 24, 13, 18, 23, 6, 18, 23, 11, 16 and 21.

Upvotes: 1

Related Questions