8 Replies - 3840 Views - Last Post: 05 October 2012 - 01:23 PM Rate Topic: -----

#1 GeneralCrackers  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 05-October 12

Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 06:31 AM

Hi everyone!

I have been working on a challenge for my beginner coding class and I hit a snag on one of the challenges. The program I am coding is supposed to bring up two prompt windows when the button is pressed, asking the user to enter how many hours they would like to travel in a day (the maximum being 20) and the speed limit. After the user enters the information the two values should be multiplied and displayed in a list box, thus giving the distance they can travel. I have scrapped my code twice already and started fresh; while I feel I'm getting closer to the solution, my code still isn't working. The two windows pop up alright and I can input values, but it keeps entering a 0 in the list box after the second value is entered. Any quick help would be appreciated, I am under a bit of a time crunch and this program has me about ripping my hair out.

This is my code for when the button is clicked.

   Dim strSpeedLimit As String
        Dim strHours As String
        Dim decSpeedLimit As Decimal
        Dim decHours As Decimal
        Dim decDistance As Decimal = decSpeedLimit * decHours
        Dim strNormalMessage1 As String = "Enter the Speed Limit"
        Dim strNormalMessage2 As String = "Enter how many hours you would like to travel"
        Dim strInputMessage1 As String = "Enter the Speed Limit"
        Dim strInputHeading1 As String = "Enter Speed"
        Dim strInputMessage2 As String = "Enter how many hours you would like to travel in one day"
        Dim strInputHeading2 As String = "Enter Hours"
        Dim strNegativeError As String = "Enter a positive number"
        Dim strOver20Error As String = "Error - Enter a number less than or equal to twenty"
        Dim strNonNumericError As String = "Error - Enter a numeric value"
        Dim strErrorHeader As String = "Error"
        Dim intNumberOfEntries As Integer = 1
        Dim intMaxNumberOfEntries As Integer = 7

        strSpeedLimit = InputBox(strInputMessage1, strInputHeading1)
        strHours = InputBox(strInputMessage2, strInputHeading2)


        If IsNumeric(strSpeedLimit) Then
            decSpeedLimit = Convert.ToDecimal(strSpeedLimit)
            If decSpeedLimit > 0 And decHours > 0 And decHours < 20 Then
                strInputMessage1 = strNormalMessage1


            Else
                strInputMessage1 = strNegativeError
            End If
        Else
            strInputMessage1 = strNonNumericError
        End If

        If IsNumeric(strHours) Then
            decHours = Convert.ToDecimal(strHours)
            If decHours > 0 And decHours < 20 Then
                strInputMessage2 = strNormalMessage2



            Else
                strInputMessage2 = strOver20Error
            End If
        Else
            strInputMessage2 = strNonNumericError
        End If


        lstDistance.Items.Add(decDistance.ToString)
        intNumberOfEntries += 1





    End Sub 


Sorry for how messy the code is. Any help would be appreciated greatly.

Is This A Good Question/Topic? 0
  • +

Replies To: Visual Studio 2010 Distance Traveled Challenge...Help!

#2 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1605
  • View blog
  • Posts: 5,162
  • Joined: 25-September 09

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 06:47 AM

If you debug, you will find that you are never setting decHours to anything after you initialize it in the declaration.

Also, yuo calculate decdistance before you have any values so

Dim decSpeedLimit as Decimal'= 0 by default
dim decHours as Decimal '=0 by default
Dim decDistance as decimal = decSpeedLimit * decHours


so what you have here is decDistance = 0 * 0

Also in your if statement for decSpeedLimit, you also check if decHour > 0 but it's not at that point.

Then you check decHours later but you never recalculate decDistance against the new values.
    *Prompt User for Input
    *convert your strings from the (Yuck!!) inputbox (don't forget to react if it can't be converted)
    *calculate your values
    *add the value to the listbox


Is it required that you use input boxes or can you use 2 numericupdown controls instead? (of course I think the NUD control has issues with decimals)

This post has been edited by AdamSpeight2008: 05 October 2012 - 07:24 AM
Reason for edit:: Adding inline and code tags

Was This Post Helpful? 2
  • +
  • -

#3 GeneralCrackers  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 05-October 12

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 07:38 AM

Thanks for the quick response, you're a life saver! I changed the order of some of the code so that the distance calculation is done after both speed limit and hours are confirmed to be numeric and positive and now it is properly calculating the values. I also removed some unnecessary code and spaces.

The problem I am having now is that if a non-numeric or negative number is entered, the error message displays and the user is prompted to enter the information again, but when the final calculation is done the non-numeric or negative value is included in the final equation. How would I fix this? You can see my attempt at fixing it within the strSpeedLimit If statement under the first Else. Also, as far as the input boxes go, unfortunately I have to use them because this chapter of the book covers them.

Here is my revised code:

  
        Dim strSpeedLimit As String
        Dim strHours As String
        Dim decSpeedLimit As Decimal
        Dim decHours As Decimal
        Dim decDistance As Decimal
        Dim strNormalMessage1 As String = "Enter the Speed Limit"
        Dim strNormalMessage2 As String = "Enter how many hours you would like to travel"
        Dim strInputMessage1 As String = "Enter the Speed Limit"
        Dim strInputHeading1 As String = "Enter Speed"
        Dim strInputMessage2 As String = "Enter how many hours you would like to travel in one day"
        Dim strInputHeading2 As String = "Enter Hours"
        Dim strNegativeError As String = "Enter a positive number"
        Dim strOver20Error As String = "Error - Enter a number less than or equal to twenty"
        Dim strNonNumericError As String = "Error - Enter a numeric value"
        Dim strErrorHeader As String = "Error"



        strSpeedLimit = InputBox(strInputMessage1, strInputHeading1)
        If IsNumeric(strSpeedLimit) Then
            decSpeedLimit = Convert.ToDecimal(strSpeedLimit)
            If decSpeedLimit > 0 Then
                strInputMessage1 = strNormalMessage1

            Else
                MessageBox.Show(strNegativeError, strErrorHeader)
                strSpeedLimit = " "
                strSpeedLimit = InputBox(strInputMessage1, strInputHeading1)
            End If
        Else
            MessageBox.Show(strNonNumericError, strErrorHeader)
        End If

        strHours = InputBox(strInputMessage2, strInputHeading2)

        If IsNumeric(strHours) Then
            decHours = Convert.ToDecimal(strHours)
            If decHours > 0 And decHours < 20 Then
                strInputMessage2 = strNormalMessage2
                decDistance = decSpeedLimit * decHours
                lstDistance.Items.Add(decDistance.ToString)

            Else
                MessageBox.Show(strOver20Error, strErrorHeader)
            End If
        Else
            MessageBox.Show(strNonNumericError, strErrorHeader)
        End If

    End Sub
End Class


Was This Post Helpful? 0
  • +
  • -

#4 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 08:16 AM

Separate your code into different methods. Then you can test the methods by themselves. You can also work on each bit of logic. It also cuts down on the amount of variables available. My example:
Public Function Test
   Dim hours As Double = GetHoursFromUser()
   // notice we now have the variable 'hours'
   // that we know is good.  If the function works,
   // it is not possible for us to have "bad" data
   // at this point.  Any bad data was consumed
   // and destroyed in the function.
   Messagebox.Show(hours.ToString())
End Function

Public Function GetHoursFromUser As Double
   Dim hours As Double = 0
   Dim valid As Boolean = False
   Dim response As String
   
   Do
      response = InputBox(strInputMessage1, strInputHeading1)
      Double.TryParse(response, out hours)
      valid = IsValidHours(hours)
      If (valid == False)
         // no need to reset any of the variables since
         // the code will loop back and they will all
         // be set again
         MessageBox.Show(strNonNumericError, strErrorHeader)
      End If
   While (valid == False)

   return hours
End Function

Public Function IsValidHours(Hours As Double) As Boolean
   If (Hours <= 0)
      return False
   End If
   If (Hours > 20)
      return False
   End If
   return True
End Function


Now the functions are short and concise. They are named so anyone should know what they do. It is easier to debug, test, and change. Let's say the requirements change to allow up to 24 hours a day. I can look at the function names and guess that IsValidHours is the most likely function that needs a change. It is a good habit to get into early.

*Warning: I am a C# coder and wrote this by hand. It probably has syntax errors.
Was This Post Helpful? 1
  • +
  • -

#5 GeneralCrackers  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 05-October 12

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 10:37 AM

Thank you for the assistance. I tried re-coding the application using your suggestions, but now I seem to be getting quite a few errors showing up when I debug. I'm not quite sure where to go from here to fix these problems.

Also, I read the assignment wrong; what I actually have to do is have two text boxes on the gui where the user may enter the speed limit and how many days they wish to travel. When the Distance button is clicked an input box appears asking the user to enter how many hours they want to travel each day, then the three values are multiplied and added to the list box.

Here is my current code and error list:

Private Sub btnDistance_Click(sender As System.Object, e As System.EventArgs) Handles btnDistance.Click
        '  Clicking the Distance button displays a prompt window that
        ' ask users to enter the number of Hours they would like 
        ' to travel each day and the result is generated by using the input
        ' from the Speed Limit and Days Box along with the Hours.
        ' The result is displayed in the list box.



        '''''''
        

        Dim txtSpeedLimit As String
        Dim txtDays As String
        Dim dblSpeedLimit As Double
        Dim dblDays As Double
        Dim strNegativeError As String = "Enter a positive number"
        Dim strNonNumericError As String = "Error - Enter a numeric value"
        Dim strErrorHeader As String = "Error"


        If IsNumeric(txtSpeedLimit) And IsNumeric(txtDays) Then
            dblSpeedLimit = Convert.ToDouble(txtSpeedLimit)
            dblDays = Convert.ToDouble(txtDays)
            If dblSpeedLimit > 0 And dblDays > 0 Then

            Else
                MessageBox.Show(strNegativeError, strErrorHeader)
            End If
        Else
            MessageBox.Show(strNonNumericError, strErrorHeader)
        End If




    End Sub
    Public Function Test() As Double
        Dim Hours As Double = GetHoursFromUser()
        MessageBox.Show(Hours.ToString())
    End Function

    Public Function GetHoursFromUser() As Double
        Dim Hours As Double = 0
        Dim valid As Boolean = False
        Dim response As String
        Dim strInputMessage1 As String = "Enter How Many Days You'd Like to Travel"
        Dim strInputHeading1 As String = "Enter Days"
        Dim strNonNumericError As String = "Error - Enter a positive numeric value that is less than 20"
        Dim strErrorHeader As String = "Error"

        While (valid = True)
            response = InputBox(strInputMessage1, strInputHeading1)
            Double.TryParse(response, Hours)
            valid = IsValidHours(Hours)
            Dim dblDistance As Double = (dblSpeedLimit * Hours) * dblDays

            lstDistance.Items.Add(dblDistance & " Miles")
            If (valid = False) Then
                MessageBox.Show(strNonNumericError, strErrorHeader)
            End If


            Return Hours
        End While
    End Function

    Public Function IsValidHours(Hours As Double) As Boolean
        If Hours <= 0 Then
            Return False
        End If
        If Hours > 20 Then
            Return False
        End If
        Return True
    End Function


End Class






Warning 1 Variable 'txtSpeedLimit' is used before it has been assigned a value. A null reference exception could result at runtime.

Warning 2 Variable 'txtDays' is used before it has been assigned a value. A null reference exception could result at runtime.

Warning 3 Function 'Test' doesn't return a value on all code paths. Are you missing a 'Return' statement?

Error 4 'dblSpeedLimit' is not declared. It may be inaccessible due to its protection level.

Error 5 'dblDays' is not declared. It may be inaccessible due to its protection level.
Was This Post Helpful? 0
  • +
  • -

#6 lucky3  Icon User is offline

  • Friend lucky3 As IHelpable
  • member icon

Reputation: 231
  • View blog
  • Posts: 765
  • Joined: 19-October 11

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 11:11 AM

In your previous code, you assigned values to variables, before you started to calculate. You need to do the same. Look at lines 18 and 19 of your previous code, and you'll see the difference with lines 13 to 22 in your last post's code.
Was This Post Helpful? 1
  • +
  • -

#7 torind_2000  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 57
  • View blog
  • Posts: 292
  • Joined: 22-August 11

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 11:13 AM

View PostGeneralCrackers, on 05 October 2012 - 01:37 PM, said:

Warning 1 Variable 'txtSpeedLimit' is used before it has been assigned a value. A null reference exception could result at runtime.

Warning 2 Variable 'txtDays' is used before it has been assigned a value. A null reference exception could result at runtime.

Warning 3 Function 'Test' doesn't return a value on all code paths. Are you missing a 'Return' statement?

Error 4 'dblSpeedLimit' is not declared. It may be inaccessible due to its protection level.

Error 5 'dblDays' is not declared. It may be inaccessible due to its protection level.


Sir, these errors are pretty self explanatory.
First 2 are the similar to the original problem that CharlieMay helped you with.
3rd problem is there's no return in that TEST function.
4 and 5 mean you may have declared the variable, but not in the proper scope.
Was This Post Helpful? 1
  • +
  • -

#8 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 11:18 AM

Warnings 1 & 2:
You declare 'txtSpeedLimit' in line 13 and use it in line 22. What is the value of 'txtSpeedLimit'? If you haven't set it, it is NULL. The compiler is warning you that passing around a NULL string object can lead to errors. Make sure you set something to your strings before you use them.

3,4, &5:
I may have pushed you beyond your current skill level. Have you gone over concepts like Function, Scope, or Do..While?

If you have not covered these subjects yet, I suggest you go back to your code in post #3. One solution is to change how you handle bad input. Display the message on what is bad. Instead of trying to ask for the value again just stop right there. The return keyword will end a function and keep anything else from processing.

strSpeedLimit = InputBox(strInputMessage1, strInputHeading1)
If !IsNumeric(strSpeedLimit) Then
   return
End If
// any other checks you want to do can be done here
// ie negative values or too high of values

// at this point in the code, you know that strSpeedLimit is a valid number


Was This Post Helpful? 1
  • +
  • -

#9 GeneralCrackers  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 05-October 12

Re: Visual Studio 2010 Distance Traveled Challenge...Help!

Posted 05 October 2012 - 01:23 PM

Thanks for the all the help, everyone. I finally finished the application; error free!

I removed the functions and ended up using a series of nested If statements.

@Robin19, yeah, some of that stuff was unfamiliar to me. Thus far we haven't worked with Functions, Scope, Do...While, or Return. We just started covering a basic Do Until Loop. Thanks for the help, your last comment got me back on the right track; the Return statement worked wonders.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1