Katana24
Katana24

Reputation: 8959

Why isn't this running?

I have this code below:

<html>

<head>
    <title> Eloquent Javascript Ex 2 </title>

<script language = "javascript">

    /*
    function twoPowerTen()
    {
        var result = 1;
        var counter = 0;

        while( counter < 10 )
        {
            result = 2 * result;
            document.writeln( result );
            counter = counter + 1;
        }
    }   

    int limit = 1;

    for( int y = 0; y < 5; y++ )
    {
        for( int x = 0; x < limit; x++ )
        {
            System.out.print( "*" );
        }
        System.out.println();
        limit = limit + 1;
    }
    */

    function drawTriangle()
    {
        var limit = 1;

        for( var y = 0; y < 5; y++ )
        {
            for( var x = 0; x < limit; x++ )
            {
                document.write( "*" );
            }
            document.write( "<br>" );
            limit = limit + 1;
        }
    }

    function whileDrawTriangle()
    {
        var limit = 1;
        var x, y = 0;

        while( y < 5 )
        {
            while( x < limit )
            {
                document.write( "*" );
                x++;
            }
            limit = limit + 1;
            y++;
        }
    }

</script>

</head>

<body>
<input type = "button" value = "Draw # Triangle" onClick = "whileDrawTriangle()" />
</body>


</html>

which doesn't seem to want to run when I hit the button - it's suppose to print a triangle of astericks to the screen. BTW I know the HTML isn't well constructed but the point is to just implement basic javascript as Im getting to grips with it's fundamentals.

What's the problem?

Upvotes: -1

Views: 110

Answers (3)

Jack
Jack

Reputation: 10993

Your drawTriangleMethod is never called, you can just add a button to call it, or change your onClick to call that function. As for your whileDrawTriangle method you are only initializing your y variable to 0, while x is remaining undefined and therefore when it comes to the loop it fails the test x < limit.

If you want to initialize both x and y you need to do so explicitly

For example

 var x = 0, y= 0;

Here's a jsBin

Upvotes: 2

dchhetri
dchhetri

Reputation: 7136

You need to initialize you variable x to 0;

Upvotes: 1

j08691
j08691

Reputation: 207861

If you change your code to onClick = "drawTriangle()" instead of onClick = "while DrawTriangle()" it works fine.

jsFiddle example

Upvotes: 1

Related Questions