What's Wrong With this Code? (#3)

Here is a Visual Basic program with bowling scores in a multi-dimensional array. Two players bowled three games each. The program tries to display the total score for each bowler, but has a small problem. Can you spot it?

Module Module1

  
Sub Main()

    
Dim allScores As Integer(,) = _
        {{101, 128, 143}, {123, 115, 116}}

    
' for each player
    For i As Integer = 0 To allScores.GetUpperBound(0)

      
Dim score As Integer

      ' for each game
      For j As Integer = 0 To allScores.GetUpperBound(1)
        score = score + allScores(i, j)
      
Next

      Console.WriteLine("Player {0} score: {1}", i + 1, score)

    
Next

  End Sub

End
Module

Print | posted @ Tuesday, August 15, 2006 2:30 AM

Comments on this entry:

Gravatar # re: What's Wrong With this Code? (#3)
by Eber Irigoyen at 8/15/2006 3:07 AM

due to the scope, variable score needs to be initialized to zero
  
Gravatar # re: What's Wrong With this Code? (#3)
by Abhijit at 8/15/2006 3:13 AM


variable score should be initialised to 0

Dim score As Integer = 0
  
Gravatar # re: What's Wrong With this Code? (#3)
by Geoff Appleby at 8/15/2006 3:39 AM

Ha, an easy one :)

score might look like it's declared inside the first loop, but when compiled the declaration moves to the top of the mothod.

The end result is that the printed score for player 2 is the actually the entire sum.

By modifying it to be Dim score as Integer = 0 (or exlicitly assinging 0 on the next line) the declaration is still at the top, but the assignment to 0 happens on every iteration.
  
Gravatar # re: What's Wrong With this Code? (#3)
by scott at 8/15/2006 3:48 AM

You guys nailed it! Too easy!
  
Gravatar # re: What's Wrong With this Code? (#3)
by Justin King at 8/15/2006 4:27 AM

It's not written in C# :P
  
Gravatar # re: What's Wrong With this Code? (#3)
by James at 8/15/2006 7:11 AM

It is written in Visual Basic?

:o)
  
Gravatar # re: What's Wrong With this Code? (#3)
by scott at 8/15/2006 11:54 AM

James, Justin:

In C# this would yield a "use of unassigned local" warning. In a sense you are right.
  
Gravatar # re: What's Wrong With this Code? (#3)
by Eric D. Burdo at 8/15/2006 2:43 PM

Geoff... VB Classic doesn't have scope level variables.

VB.Net does. So the declaration doesn't get moved to the top. It stays inside the block it is declared in.

So you need to either a) Declare the score at the top, then initialise to 0 inside the loop, or b) initialise to 0 inside the loop when you declare the score variable.

I would prefer method b if I didn't need the score outside of the first loop.
  
Gravatar # re: What's Wrong With this Code? (#3)
by marshall at 8/15/2006 8:37 PM

can anyone tell me a reason why vb.net behaves like this?

i can't see any good reason for keeping a variables value when it goes out of scope.
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 1 and 7 and type the answer here: