Math.Round Variable? Visual basic - visual-studio-2010

I'm writing a program for my visual basic class that computes the prices of cans per pound. I have the program running, but I need to round the cents up to the nearest dollar. How can I do this in vb? Is it possible to round a decimal variable?
I'm sorry if this sounds stupid, I am a newb lol.
Here is my code.
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Variables
Dim cans As Integer
Dim canPounds As Integer
Dim canPoundTotal As Decimal
Dim canWorth As Decimal = 0.75
Dim cansNeeded As Integer
'Conversions
cans = Convert.ToInt32(txtGoal.Text)
'Calculation
canPounds = cans / 24
canPoundTotal = canPounds * canWorth
cansNeeded = 33000 - cans
If cboNeed.SelectedIndex = 0 Then
lblOutput.Text = cansNeeded.ToString + " cans need to be collected to reach your goal"
ElseIf cboNeed.SelectedIndex = 1 Then
lblOutput.Text = canPoundTotal.ToString("C") & " will be earned by collecting cans for recycling"
End If
End Sub
Private Sub cboNeed_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboNeed.SelectedIndexChanged
If cboNeed.SelectedIndex = 0 Then
lblDesc.Text = "Target Goal Amount"
btnCalculate.Text = "Find Target Amount of Cans"
ElseIf cboNeed.SelectedIndex = 1 Then
lblDesc.Text = "Cans Collected"
btnCalculate.Text = "Find Amount Earned"
End If
End Sub
End Class

You can use the function: Math.Round(value)

Related

Subtracting in loops associated with variables

I am trying to make a loop that keeps subtracting from the initial amount of each item until the amount is less than the price of an item. It is also supposed to show the last item purchased before the amount was less than the price of an item. Cars cost $310,000, rings cost $12,500, Diamonds cost $150,000 and chocolate costs $51. The items are in a file on my computer, and the following is an example of what it should look like.
Sample Input:
350000
Car
Ring
Diamond
Car
Chocolate
Diamond
Sample Output:
Ring
$27, 500 left
For some reason, the value I get the wrong value when I subtract, but I can't figure out why. I've declared the prices for each item and checked multiple times to make sure they are correct, and I've checked my code, but I still don't know why I get the wrong output.
Private Sub btnS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnS.Click
Dim inFile As StreamReader = New StreamReader("serena.txt")
'Declare the varibles
Dim variableName As String
' the current items from the file
Dim amount As Integer
Dim price As Integer
amount = Val(inFile.ReadLine())
Do
'read in the words
variableName = inFile.ReadLine()
'determine each item's price
If variableName = "car" Then price = 310000
If variableName = "ring" Then price = 12500
If variableName = "diamond" Then price = 150000
If amount >= price Then amount = amount - price
Loop Until amount < price
'output the results
Me.lblOutput.Text = variableName & _
vbNewLine & "Serena has " & Format(amount, "currency") & " left"
End Sub
Take a close look at the COMMENTS I've placed into the code below:
Private Sub btnS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnS.Click
Dim fileName As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "serena.txt")
Dim inFile As New StreamReader(fileName)
Dim itemToPurchase As String
Dim lastThingBought As String = "{ Nothing Bought }" ' what if they can't afford anything?
Dim balance As Integer
Dim price As Integer
Dim somethingBought As Boolean
balance = Val(inFile.ReadLine())
Do
somethingBought = False ' we don't know yet if we can purchase the next item
'read in the words
itemToPurchase = inFile.ReadLine().ToLower().Trim() ' make sure it has no spaces and is lowercase to match below
'determine each item's price
Select Case itemToPurchase
Case "car"
price = 310000
Case "ring"
price = 12500
Case "diamond"
price = 150000
Case "chocolate" ' FYI: you were missing chocolate in your code
price = 51
Case Else ' it could happen!
MessageBox.Show(itemToPurchase, "Unknown Item!")
lblOutput.Text = "Error in file"
Exit Sub
End Select
If balance >= price Then
somethingBought = True
balance = balance - price
' we need to store the last thing purchased,
' because "itemToPurchase" gets replaced with the thing you couldn't afford
lastThingBought = itemToPurchase
End If
' Need to check for the end of file being reached...
' ...they may purchase everything in the file and still have money left!
Loop While Not inFile.EndOfStream AndAlso somethingBought
'output the results
Me.lblOutput.Text = lastThingBought &
vbNewLine & "Serena has " & Format(balance, "currency") & " left"
End Sub

Stumped why I'm getting "System.ArgumentOutOfRangeException" error

I've run into a problem with a program for my Visual Basic class that has me stumped. The assignment is a Guessing Game, I'm to create a private sub that generates a random number within the bounds of a user input (ie... 1 - 100). I seem to have this functional with the exception of telling the computer to guess lower. Currently if I press "Higher" the game continues, but if I press "Lower" the error is thrown with "minValue cannot exceed maxValue". If the output in the text box is higher than my lownum variable, why am I getting this error?
The bolded code is the code I have written, everything else was provided.
Public Class frmGuess
Dim highNum As Integer
Dim lowNum As Integer
Dim guess As Integer
Private Sub frmGuess_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show("Lets Play a Game!")
'Fixed the grammatical error below - "Think of an whole number" is incorrect.
MessageBox.Show("Think of a whole number -- DON'T TELL ME!")
MessageBox.Show("Now give me a range you want me to guess in... like 1 to 100.")
lowNum = InputBox("Whats the starting value?", "Lowest Value")
highNum = InputBox("Whats the ending value?", "Highest Value")
lblTitle.Text = "I am guessing a number between " & lowNum & " and " & highNum & "."
newGuess()
End Sub
**Sub newGuess()
'
' ITS GONE! OH NO!
'
'New Guess Sub - Calculates a response based on the input from user and recalculates responses to guess the number.
'Setting New Variables
Dim random As New Random
'Generating Response
txtGuess.Clear()
txtGuess.Text = random.Next(lowNum, highNum + 1)
End Sub**
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
highNum = guess - 1
newGuess()
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
lowNum = guess + 1
newGuess()
End Sub
Private Sub btnCorrect_Click(sender As Object, e As EventArgs) Handles btnCorrect.Click
MessageBox.Show("I win. I told you I was awesome.")
Close()
End Sub
Private Sub txtGuess_TextChanged(sender As Object, e As EventArgs) Handles txtGuess.TextChanged
End Sub
End Class
Figured it out, the program functions as expected.

"User-defined type not defined" Error

Hi im trying to create a simple program involving an object and a class within
VB 6.0.
The error message i get is: "User-defined type not defined"
The highlighted code that VB suspects is "Dim Bob As Ball"
My defined class is as follows:
Dim Bob As Object
Public Sub Ball()
Dim Circlex As Integer
Dim Circley As Integer
Public Sub makeBall()
Circlex = 3000
Circley = 3000
End Sub
Private Sub moveBall()
Circle (Circlex, Circley), 200
End Sub
End Sub
My code for the only form in my project is:
Private Sub Command1_Click()
Command1.Visible = False
Command1.Enabled = False
vbalProgressBar1.Visible = True
Timer1.Enabled = True
Beep
End Sub
Private Sub Form_Load()
Form1.Width = 6000
Form1.Height = 6000
Dim Bob As Ball
Dim Bob As New Ball
End Sub
Private Sub Form_Unload(Cancel As Integer)
If MsgBox("Are you sure you want to be a quitter?!"
, vbYesNo,"Quit?") = vbYes Then
Unload Me
Set Form1 = Nothing
Else
Cancel = 1
End If
End Sub
Private Sub Timer1_Timer()
Bob = moveBall(Circlex, Circley)
End Sub
Im not sure why the suspected line of code is incorrect, but any help would be appreciated!
VB6 doesn't use code style that you coded.
You have to follow these method to make code work with your intention.
1. make classmodule
2. set its name 'Ball'
3. paste this code on classmodule
Dim Circlex As Integer
Dim Circley As Integer
Public Sub makeBall()
Circlex = 3000
Circley = 3000
End Sub
Private Sub moveBall()
Circle (Circlex, Circley), 200
End Sub
paste code on your form
Private Sub Command1_Click()
Command1.Visible = False
Command1.Enabled = False
vbalProgressBar1.Visible = True
Timer1.Enabled = True
Beep
End Sub
Private Sub Form_Load()
Form1.Width = 6000
Form1.Height = 6000
Dim Bob As New Ball
End Sub
Private Sub Form_Unload(Cancel As Integer)
If MsgBox("Are you sure you want to be a quitter?!"
, vbYesNo,"Quit?") = vbYes Then
Unload Me
Set Form1 = Nothing
Else
Cancel = 1
End If
End Sub
Private Sub Timer1_Timer()
Bob.moveBall(Circlex, Circley)
End Sub
Additionally, VB6 doesn't support style like
Sub A()
Sub B()
End Sub
End Sub

How to change the location of a picture box in VB 2010 using the arrow or wasd keys?

I only have access to the internet at school, so the filters get in the way of any real research. I'm currently coding an rpg for a school project but it's difficult to get the avatar to move on a map. Here's my pathetic code so far:
Public Class Map1
Private Sub USER_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
User.Top = User.Top - 1
End Sub
Private Sub USER_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
User.Top = User.Bottom + 1
'User.Location.X = 200
End Sub
End Class
I have the following problems with it:
User.location.x = 200 had syntax errors when I deleted the x and when I didn't.
The player also had to continually press the keys to move.
both I do not know how to correct.
Any help at all is greatly appreciated as it's for my final grade.
You can put it in a timer_tick to loop over it, that is what I do.
And the correct version of User.Location.X = 200 is:
User.location = new point(200, User.location.y)
nvm found the solution.
Here it is for anyone else how might need the code in the future.
Private Sub Map_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.Up Then
User.Location = New Point(User.Location.X, User.Location.Y - 5)
ElseIf e.KeyCode = Keys.Down Then
User.Location = New Point(User.Location.X, User.Location.Y + 5)
ElseIf e.KeyCode = Keys.Left Then
User.Location = New Point(User.Location.X - 5, User.Location.Y)
ElseIf e.KeyCode = Keys.Right Then
User.Location = New Point(User.Location.X + 5, User.Location.Y)
End If
Module
Public Sub MovePictureBox(ByRef PictureBox As PictureBox)
Tiempo.Tag = PictureBox
AddHandler PictureBox.Parent.KeyDown, AddressOf Parent_KeyDown
AddHandler PictureBox.Parent.KeyUp, AddressOf Parent_KeyUp
AddHandler CType(PictureBox.Parent, Form).Load, AddressOf Parent_Load
End Sub
Private Up, Down, Left, Right As Boolean
WithEvents Tiempo As New Timer() With {.Interval = 1}
Private Sub Tiempo_Tick() Handles Tiempo.Tick
If Up Then Tiempo.Tag.Top -= 2
If Down Then Tiempo.Tag.Top += 2
If Left Then Tiempo.Tag.Left -= 2
If Right Then Tiempo.Tag.Left += 2
End Sub
Private Sub Parent_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
If e.KeyCode = Keys.Up Then Up = True
If e.KeyCode = Keys.Down Then Down = True
If e.KeyCode = Keys.Left Then Left = True
If e.KeyCode = Keys.Right Then Right = True
Tiempo.Enabled = True
End Sub
Private Sub Parent_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
Tiempo.Enabled = False
Up = False : Down = False : Right = False : Left = False
End Sub
Private Sub Parent_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
sender.KeyPreview = True
End Sub
End Module

Creating a strip of selectable letters for a form

I wish to display a list of letters from a through z on a form.
Each letter needs to be clickable with that value being passed as a click argument.
Aside from creating 26 letters and using the click event of each letter does anyone know of a quick way to do this?
I know how to load dynamic controls etc and how to do it that way. Just wondering if anyone knew of a clever way to do this?
Cheers
You can use a FlowLayoutPanel and a loop like this:
private void button1_Click(object sender, EventArgs e)
{
flowLayoutPanel1.FlowDirection = FlowDirection.LeftToRight;
flowLayoutPanel1.AutoSize = true;
flowLayoutPanel1.WrapContents = false; //or true, whichever you like
flowLayoutPanel1.Controls.Clear();
for (char c = 'A'; c <= 'Z'; c++)
{
Label letter = new Label();
letter.Text = c.ToString();
letter.AutoSize = true;
letter.Click += new EventHandler(letter_Click);
flowLayoutPanel1.Controls.Add(letter);
}
}
private void letter_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked on " + ((Label)sender).Text);
}
This is the "dynamic way" I would do it in. I know you asked for other clever ways to do it in but I think this is the most accepted way to do it.
This will produce those buttons and add a click-handler that takes the button as sender. It will also see to that the buttons location wraps if outside of the forms width.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ButtonSize As New Size(20, 20)
Dim ButtonLocation As New Point(10, 20)
For p As Integer = Asc("A") To Asc("Z")
Dim newButton As New Button
If ButtonLocation.X + ButtonSize.Width > Me.Width Then
ButtonLocation.X = 10
ButtonLocation.Y += ButtonSize.Height
End If
newButton.Size = ButtonSize
newButton.Location = ButtonLocation
newButton.Text = Chr(p)
ButtonLocation.X += newButton.Width + 5
AddHandler newButton.Click, AddressOf ButtonClicked
Me.Controls.Add(newButton)
Next
End Sub
Sub ButtonClicked(ByVal sender As Object, ByVal e As System.EventArgs)
MsgBox(CType(sender, Button).Text)
End Sub
End Class
alt text http://img235.imageshack.us/img235/2267/testoa6.jpg
Draw a string on a control, then match mouse clicks to the character positions on the form. It's actually easier than it sounds (this is adapted from standard documentation on MeasureCharacterRanges, which simplifies the entrire task). The example is drawn on a form, it would be simple enough to make this into a user control.
In this example, clicking on a letter will cause a messagebox to appear, telling you which letter you just clicked.
Hope it helps.
P.S. Please forgive "magic numbers" e.g. "knowning" there'll be 25 items in the array, this is just a sample after all :)
Public Class Form1
Const LETTERS As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Private letterRects(25) As System.Drawing.RectangleF
Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
Dim index As Integer = -1
Dim mouseP As Point = Me.PointToClient(MousePosition)
For i As Integer = 0 To 25
If letterRects(i).Contains(mouseP.X, mouseP.Y) Then
index = i
Exit For
End If
Next
If index >= 0 Then
MessageBox.Show("Letter = " + LETTERS(index).ToString())
End If
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
' Set up string.
Dim stringFont As New Font("Times New Roman", 16.0F)
' Set character ranges
Dim characterRanges(26) As CharacterRange
For i As Integer = 0 To 25
characterRanges(i) = New CharacterRange(i, 1)
Next
' Create rectangle for layout, measurements below are not exact, these are "magic numbers"
Dim x As Single = 50.0F
Dim y As Single = 50.0F
Dim width As Single = 400.0F
Dim height As Single = 40.0F
Dim layoutRect As New RectangleF(x, y, width, height)
' Set string format.
Dim stringFormat As New StringFormat
stringFormat.FormatFlags = StringFormatFlags.FitBlackBox
stringFormat.SetMeasurableCharacterRanges(characterRanges)
' Draw string to screen.
e.Graphics.DrawString(letters, stringFont, Brushes.Black, _
x, y, stringFormat)
Dim stringRegions() As [Region]
' Measure two ranges in string.
stringRegions = e.Graphics.MeasureCharacterRanges(letters, _
stringFont, layoutRect, stringFormat)
For i As Integer = 0 To 25
letterRects(i) = stringRegions(i).GetBounds(e.Graphics)
Next
End Sub
End Class

Resources