I am working on a Budget calculator for a class project. Basically everything works great except one little annoying nuance.
When you don't enter a number or you enter a negative number you get an error message. However, when you accidentally type in a letter, get the error, then type in the negative number it just exits, and I want it to show that error and loop back until they enter in a positive number.
I am using VBA in Visual Studio 2012, this is a Windows Form Application.
Dim strEntertainmentHeading As String = "Entertainment Expenses"
Dim strHeading As String = "Budget Alottment"
Dim strNonNumericError As String = "Error - Enter a number for the Expense"
Dim strNegativeError As String = "Error - Enter a positive number for the Expense"
Dim strEntertainmentInput As String = "Enter the amount for Entertainment Expenses"
Dim strEntertainment As String
Dim decEntertainment As Decimal
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
Do
If strEntertainment = "" Then
Exit Sub
ElseIf IsNumeric(strEntertainment) Then
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment >= 0 Then
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
' Display error message if user entered a negative value
Else
strEntertainmentInput = strNegativeError
End If
Else
strEntertainmentInput = strNonNumericError
End If
If decEntertainment <= 0 Then
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
End If
Loop Until IsNumeric(strEntertainment) And decEntertainment >= 0
Of course, you have this problem: decEntertainment is 0 by default and after asking for input the second time, you do not Convert.ToDecimal anymore.
You avoid this type of errors if you adopt a clear coding style, like
Do
strEntertainmentInput = ''
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
If Not IsNumeric(strEntertainment) Then
strEntertainmentInput = strNonNumericError
Else
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment < 0 Then
strEntertainmentInput = strNegativeError
Else
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
End
End
Loop Until strEntertainmentInput = ''
Related
Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:
Dim strGrades As String
Dim decGrades As Decimal = 0
Dim decAverage As Decimal = 0
Dim decTotal As Decimal = 0
Dim strInputMessage As String = "Enter grade #"
Dim strInputHeading As String = "Grade"
Dim strNormalMessage As String = "Enter grade #"
Dim strNonNumericError As String = "Error - Please enter a grade"
Dim strNegativeError As String = "Error - Please enter a positive number"
Dim strCancelClicked As String = ""
Dim intMaxNumberOfEntries As Decimal = 13
Dim intNumberOfEntries As Decimal = 1
strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
If IsNumeric(strGrades) Then
decGrades = Convert.ToDecimal(strGrades)
If decGrades >= 0 Then
lstGrades.Items.Add(decGrades)
decTotal += decGrades
intNumberOfEntries += 1
strInputMessage = strNormalMessage
Else
strInputMessage = strNegativeError
End If
Else
strInputMessage = strNonNumericError
End If
If intNumberOfEntries <= intMaxNumberOfEntries Then
strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
End If
Loop
lstGrades.Sorted = True
Assuming that you have an enumerable list of numeric values, e.g. an array of Decimal, then the most succinct way to get the average of all but the two lowest values would be:
Dim average = myList.OrderBy(Function(n) n).Skip(2).Avg()
I'm not sure how much of that would be acceptable for an assignment - if that's what this is - but the part that you're asking about specifically can still be done by calling Skip(2) if you start with a list that is sorted in ascending order.
You can count the entries in the list box and remove the bottom 2 entries.
You can add them to a list and sort it.
I have this case where I need that the user enters some data. All I need is to allow the user to enter numbers from 0 to 100, if the user is entering an amount bigger than 100, than display a message like: please enter number from 0 to 100 and then show them again where they need to enter that number.
For example, Console.Write("Español: ") in the terminal is:
Español: ' the user should enter the number here
if the user enters more than 100, then display this:
Please enter number from 0 to 100. Español: ' here enter the number again
I was thinking on doing this as in the code below, with an If ... Else, but, is there a better way?
Here is the actual code:
Sub Main()
Dim Español1 As Integer
Dim Matematicas1 As Integer
Dim Ciencias1 As Integer
Dim EstudiosSociales1 As Integer
Dim Ingles1 As Integer
Dim ArtesPlasticas1 As Integer
Dim ArtesIndustriales1 As Integer
Select Case Menu
Case 2
Console.Write("Ingrese las notas: ")
Console.ReadLine()
Console.Write("Español: ")
' I was thinking on doing this
If Console.ReadLine() >= 100 Then
Console.Write("La nota debe ser 100 o menos: ")
Español1 = Console.ReadLine()
Else
Español1 = Console.ReadLine()
End If
If Español1 = True Then
Console.Write("Matematicas: ")
Matematicas1 = Console.ReadLine()
End If
Console.Write("Ciencias: ")
Ciencias1 = Console.ReadLine()
Console.Write("Estudios Sociales: ")
EstudiosSociales1 = Console.ReadLine()
Console.Write("Ingles: ")
Ingles1 = Console.ReadLine()
Console.Write("Artes plasticas: ")
ArtesPlasticas1 = Console.ReadLine()
Console.Write("Artes Industriales: ")
ArtesIndustriales1 = Console.ReadLine()
Console.Clear()
End Select
End Sub
So, any suggestions?
I'm not really experienced with VB, but try this:
Dim n as Integer
n = Console.WriteLine()
Do While n >= 100
Console.WiteLine("Enter new Value:") 'Sorry, no pienso la lengua español :(
n = Console.ReadLine()
Loop
Edit 3.0
Add your subject names into the array subjects.
Sub Main()
Dim subjects As Array = {"Math", "English", "German"} 'Three example names
Dim subjectsInt As New Dictionary(Of String, Integer)
Dim i, input As Integer
Dim check, FirstTry As Boolean
For i = 0 To (subjects.Length - 1)
check = False
FirstTry = True
Do
If FirstTry = True Then
Console.WriteLine(subjects(i) & ": ")
FirstTry = False
Else
Console.WriteLine("Please enter a value between 1 and 100" & " (" & subjects(i) & "):")
End If
input = Console.ReadLine()
If input <= 100 And input > 0 Then
subjectsInt.Add(subjects(i), input)
check = True
End If
Loop While check = False
Next
For i = 0 To (subjects.Length - 1)
Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
Next
Console.ReadLine()
End Sub
Well I dont know VBA unfortunately . But I believe in every language is the same. You do a do {}while cycle and in the while you check if you conditions are met. And until they are met you continue reading from the console. Good look with your VBA :)
I'm trying to finish a project for class that calculates the occupancy rate of a hotel using an InputBox object. However, the variables are getting permanently set as the first value entered.
Allow me to clarify what is happening. I click the button to bring up the InputBox I enter a number e.g. 10, then I click ok, then I enter a new number for the second one e.g. 7, but the list box displays both as the first one. Once I enter all the numbers for the Rooms Sold I then continue to enter the values for Rooms Available, but the number form the first loop somehow carried over to the second one and WILL NOT change.
What can I do to make it so the variable is reset for each iteration of the loop. I have it set the variable back to 0 after it has added itself to the total and the list, but it won't change.
And i did do research. The MSDN knowledge base was no help, I could only find one question on here like this and he just forgot to define a string, and I tried Google but to no avail.
Here is my code:
Public Class frmOccupancyRateCalculator
Private Sub frmOccupancyRateCalculator_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstRoomsSold.Items.Clear()
lstRoomsAvailable.Items.Clear()
End Sub
Private Sub btnEnterRoomSales_Click(sender As Object, e As EventArgs) Handles btnEnterRoomSales.Click
' Declare the arithimetic and message variables.
Dim intRoomsSold As Integer
Dim intRoomsAvailable As Integer
Dim intTotalRooms As Integer
Dim intTotalRoomsSold As Integer
Dim intTotalRoomsAvailable As Integer
Dim intRoomsSoldNumberOfEntries As Integer = 1
Dim intRoomsAvailableNumberOfEntries As Integer = 1
Dim intNumberOfEntries As Integer = 1
Dim intMaxNumberOfEntries As Integer = 7
Dim decOccupancyRate As Decimal
Dim strRoomsSold As String
Dim strRoomsSoldInputMessage As String = "Enter the number of rooms sold for floor #"
Dim strRoomsSoldInputHeading As String = "Enter Rooms Sold"
Dim strRoomsSoldNormalMessage As String = "Enter the number of rooms sold for floor #"
Dim strRoomsSoldNonNumericError As String = "Error - Non-Numeric value entered. Please enter a whole number of rooms sold for floor #"
Dim strRoomsSoldNegativeError As String = "Error - Negative number entered. Please enter a whole number greater than zero of rooms sold for floor #"
Dim strRoomsSoldDecimalError As String = "Error - Decimal number entered. Plerase enter a whole number of rooms sold for floor #"
Dim strRoomsAvailable As String
Dim strRoomsAvailableInputMessage As String = "Enter the number of rooms available for floor #"
Dim strRoomsAvailableInputHeading As String = "Enter Rooms Available"
Dim strRoomsAvailableNormalMessage As String = "Enter the number of rooms available for floor #"
Dim strRoomsAvailableNonNumericError As String = "Error - Non-Numeric value entered. Please enter a whole number of rooms available for floor #"
Dim strRoomsAvailableNegativeError As String = "Error - Negative number entered. Please enter a whole number greater than zero of rooms available for floor #"
Dim strRoomsAvailableDecimalError As String = "Error - Decimal number entered. Plerase enter a whole number of rooms available for floor #"
Dim strCancelClicked As String = ""
' Define the RoomsSoldInputMessage variables
strRoomsSold = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
' Loop to iterate until hours of travel are entered for all days of travel
Do Until intRoomsSoldNumberOfEntries > intMaxNumberOfEntries
' Is the input numeric?
If IsNumeric(strRoomsSold) Then
intRoomsSold = Convert.ToDecimal(strRoomsSold)
' Is the input greater or equal to 0?
If intRoomsSold >= 0 Then
' Is the number of rooms sold a whole number?
'If intRoomsSold Mod 1 = 0 Then
intTotalRoomsSold += intRoomsSold
lstRoomsSold.Items.Add(intRoomsSold)
intRoomsSoldNumberOfEntries += 1
intRoomsSold = 0
strRoomsSoldInputMessage = strRoomsSoldNormalMessage
' Display decimal error message
'Else
'strRoomsSoldInputMessage = strRoomsSoldDecimalError
'End If
' Display negative number error message
Else
strRoomsSoldInputMessage = strRoomsSoldNegativeError
End If
' Display non-numeric error message
Else
strRoomsSoldInputMessage = strRoomsSoldNonNumericError
End If
' Is the number of entries less than or equal to the maximum?
If intRoomsSoldNumberOfEntries <= intMaxNumberOfEntries Then
strRoomsSoldInputMessage = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
End If
Loop
' Define the RoomsAvailableInputMessage variable
strRoomsAvailable = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
Do Until intRoomsAvailableNumberOfEntries > intMaxNumberOfEntries
' Is the input numeric?
If IsNumeric(strRoomsAvailable) Then
intRoomsAvailable = Convert.ToDecimal(strRoomsAvailable)
' Is the input greater or equal to 0?
If intRoomsAvailable >= 0 Then
' Is the number of rooms sold a whole number?
'If intRoomsAvailable Mod 1 = 0 Then
intTotalRoomsAvailable += intRoomsAvailable
lstRoomsAvailable.Items.Add(intRoomsAvailable)
intRoomsAvailableNumberOfEntries += 1
intRoomsAvailable = 0
strRoomsAvailableInputMessage = strRoomsAvailableNormalMessage
' Is the number of entries equal to the maximum number of entries?
If intRoomsAvailableNumberOfEntries = intMaxNumberOfEntries Then
intNumberOfEntries += 1
End If
' Display decimal error message
'Else
' strRoomsAvailableInputMessage = strRoomsAvailableDecimalError
' End If
' Display negative number error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNegativeError
End If
' Display non-numeric error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNonNumericError
End If
' Is the number of entries less than or equal to the maximum?
If intRoomsAvailableNumberOfEntries <= intMaxNumberOfEntries Then
strRoomsAvailableInputMessage = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
End If
Loop
' Is the number of rooms sold entries greater than 1?
If intNumberOfEntries > 1 Then
' Display result label and totals
intTotalRooms = intTotalRoomsSold + intTotalRoomsAvailable
decOccupancyRate = intTotalRoomsSold / intTotalRooms
lblResult.Visible = True
lblResult.Text = intTotalRooms & vbNewLine & intTotalRoomsSold & vbNewLine & intTotalRoomsAvailable & vbNewLine & vbNewLine & decOccupancyRate.ToString("P")
' Disable the Enter Room Sales button
btnEnterRoomSales.Enabled = False
' Display error message for no values entered
Else
MsgBox("No Rooms Sold/Available value entered")
End If
End Sub
Private Sub mnuClear_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
' This script is executed when the user taps or clicks the Clear menu item.
' It clears the Room Sales and Rooms Available ListBoxes, hides the Result label,
' enables the Enter Room Sales button.
lstRoomsSold.Items.Clear()
lstRoomsAvailable.Items.Clear()
lblResult.Visible = False
btnEnterRoomSales.Enabled = True
End Sub
Private Sub mnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
' This script is executed when the user taps or clicks the Exit menu item.
' The window is closed and the program is terminated.
Close()
End Sub
End Class
Ok I figured it out. I needed to put the strRoomsSold and strRoomsAvailable variable definitions within the loops, then remove the second sequence within the Do Until loop.
' Loop to iterate until Rooms Sold number of Entries is greater than the maximum
Do Until intRoomsSoldNumberOfEntries > intMaxNumberOfEntries
' Define the RoomsSold variable
strRoomsSold = InputBox(strRoomsSoldInputMessage & intRoomsSoldNumberOfEntries, strRoomsSoldInputHeading, " ")
If strRoomsSold = strCancelClicked Then
strRoomsSoldInputMessage = strRoomsAvailableBlankError
Else
' Is the input numeric?
If IsNumeric(strRoomsSold) Then
intRoomsSold = Convert.ToDecimal(strRoomsSold)
' Is the input greater or equal to 0?
If intRoomsSold >= 0 Then
' Is the number of rooms sold a whole number?
If intRoomsSold Mod 1 = 0 Then
intTotalRoomsSold += intRoomsSold
lstRoomsSold.Items.Add(intRoomsSold)
intRoomsSoldNumberOfEntries += 1
strRoomsSoldInputMessage = strRoomsSoldNormalMessage
' Display decimal error message
Else
strRoomsSoldInputMessage = strRoomsSoldDecimalError
End If
' Display negative number error message
Else
strRoomsSoldInputMessage = strRoomsSoldNegativeError
End If
' Display non-numeric error message
Else
strRoomsSoldInputMessage = strRoomsSoldNonNumericError
End If
End If
Loop
Do Until intRoomsAvailableNumberOfEntries > intMaxNumberOfEntries
' Define the RoomsAvailable variable
strRoomsAvailable = InputBox(strRoomsAvailableInputMessage & intRoomsAvailableNumberOfEntries, strRoomsAvailableInputHeading, " ")
' Is the input numeric?
If IsNumeric(strRoomsAvailable) Then
intRoomsAvailable = Convert.ToDecimal(strRoomsAvailable)
' Is the input greater or equal to 0?
If intRoomsAvailable >= 0 Then
' Is the number of rooms sold a whole number?
If intRoomsAvailable Mod 1 = 0 Then
intTotalRoomsAvailable += intRoomsAvailable
lstRoomsAvailable.Items.Add(intRoomsAvailable)
intRoomsAvailableNumberOfEntries += 1
strRoomsAvailableInputMessage = strRoomsAvailableNormalMessage
' Is the number of entries equal to the maximum number of entries?
If intRoomsAvailableNumberOfEntries = intMaxNumberOfEntries Then
intNumberOfEntries += 1
End If
' Display decimal error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableDecimalError
End If
' Display negative number error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNegativeError
End If
' Display non-numeric error message
Else
strRoomsAvailableInputMessage = strRoomsAvailableNonNumericError
End If
Loop
I'm trying to make a mr and mrs styled game where one user enters the answer and the other user tries to guess what the other person said. Everything works up until the part where the user's answers are compared to see who's is correct. I'm not sure what exactly is wrong. Any help is massively appreciated.
Module Module1
Sub Main()
Dim Question(4) As String
Dim P1Answer(4) As String
Dim P2Answer(4) As String
Dim P1Name As String = ""
Dim P2Name As String = ""
Dim Count As Integer = 0
Dim UserScore As Integer = 0
Const ArraySize As Integer = 5
While Count <> 4
Question(Count) = ""
Count = Count + 1
End While
Count = 0
Question(0) = " favourite colour?"
Question(1) = " age?"
Question(2) = " best friends name?"
Question(3) = " favourite food?"
Question(4) = " first pet's name?"
Console.WriteLine("Enter the name of player 1")
P1Name = Console.ReadLine
Console.WriteLine("Enter the name of player 2")
P2Name = Console.ReadLine
Console.WriteLine(P1Name & ". Please get ready to enter your answers.")
Console.WriteLine("Tell " & P2Name & " to go away while you answer the questions")
Console.WriteLine("Press enter when you are ready to begin.")
Console.ReadLine()
While ArraySize <> Count
Console.WriteLine("What is your" & Question(Count))
P1Answer(Count) = Console.ReadLine
Count = Count + 1
End While
Count = 0
Console.Clear()
Console.WriteLine("Tell " & P2Name & " to come back now.")
Console.WriteLine(P2Name & ". Please get ready to enter your answers.")
Console.WriteLine("Press enter when you are ready to begin.")
Console.ReadLine()
While ArraySize <> Count
Console.WriteLine("What is " & P1Name & "'s" & Question(Count))
P2Answer(Count) = Console.ReadLine
Count = Count + 1
End While
Count = 0
**While Count <> 5
If P1Answer(Count) = P2Answer(Count) Then
UserScore = UserScore + 1
Else
UserScore = UserScore
End If
Question(Count) = Question(Count + 1)
End While**
Console.WriteLine("Your total score is " & UserScore)
Console.ReadLine()
End Sub
End Module
I see a few issues with your code - The first one that's most commonly an issue is that capitalization may cause false wrong answers.
So, for example, Player 1 says her name is "Anne" and Player 2 answers "anne" - Your code doesn't take that into account.
The next issue is that you're not actually incrementing the Count variable.
Keeping with your style of coding, I'd suggest writing that loop this way:
Count = 0
While ArraySize <> Count
If UCase(P1Answer(Count)) = UCase(P2Answer(Count)) Then
UserScore = UserScore + 1
End If
Count = Count + 1
End While
Hope that makes sense!!
How can I multi validate a text box? I only want the user to input integer but the integer shouldn't be 0 or less, how can I do this? This is what I've done:
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
If IsNumeric(txtCopies.Text) = False Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
blabla
End If
End If
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
End If
there you go, else please explain better
you can also do
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
if not(IsNumeric(txtCopies.Text) = True) then
ErrorProvider1.SetError(txtCopies, "Numbers Only")
else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
end if
End If
It's been a long time since I've done VB but here you go:
It has to be able to convert whatever is in the text box to an integer.
to do this, it checks if the string is numeric, if it is, then the num variable takes its value (so it can be checked). If this value is greater than 0 then it says it's not valid.
It needs to be a nested If statement for this to happen.
Sub OnClick()
Dim str As String
Dim num As Integer
str = TextBox1.Text
If IsNumeric(str) Then
num = str
If num <= 0 Then
TextBox1.Text = "Sorry, not valid"
End If
Else
TextBox1.Text = "Sorry, not a number"
End If
End Sub
Dim intValue As Integer
If Not Integer.TryParse(TxtBox.Text, intValue) OrElse intValue < 0 Then
Else
End If
In your style ..
If Not IsNumeric(txtCopies.Text) And Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
Else
'Blabla
End If
End If
If interger. Parse(hours Text box. Tex)<=10 then
' code to perform calculation
Else
Message box.Show("Two many hours."," Invalid Data",MessageBoxButtons.OK)
End if