Visual Basic - Calculator II coding dilemmas - vb.net

Here is an assignment I was issued in Computer Science I [Visual Basic 2010]
Objective:
Modify the CalculatorII case study to display "ERROR" if a division by 0 is attempted. "ERROR should also be displayed if more than one decimal points are entered for a single number.
I can't get the ERROR message to show up when I divide by zero or add more decimal points. Here's what I have in coding:
Public Class Form1
Dim operand1 As Double = 0
Dim operand2 As Double = 0
Dim op As String = Nothing
Dim newOperand As Boolean = True
Private Sub Number_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
btnDot.Click, btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, _
btn6.Click, btn7.Click, btn8.Click, btn9.Click
Dim btnNumberClicked As Button = sender
If newOperand Then
Me.txtDisplay.Text = btnNumberClicked.Tag
newOperand = False
Else
Me.txtDisplay.Text &= btnNumberClicked.Tag
End If
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnClear.Click
Me.txtDisplay.Text = "0"
operand1 = 0
operand2 = 0
newOperand = True
op = Nothing
End Sub
Private Sub btnOff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
btnOff.Click
Application.Exit()
End Sub
Private Sub btnOperator_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnPlus.Click, btnMinus.Click, btnTimes.Click, btnDivide.Click, btnEqual.Click, btnIntDivide.Click
Dim operatorSelected As Button = sender
If (operand1 = 0 And op = Nothing) Or op = "=" Then
operand1 = Val(Me.txtDisplay.Text)
ElseIf (operand1 = 0 And op = "/") Then
MessageBox.Show("ERROR")
Else
operand2 = Val(Me.txtDisplay.Text)
operand1 = Calculate(operand1, operand2, op)
Me.txtDisplay.Text = operand1
End If
op = operatorSelected.Tag
newOperand = True
End Sub
Function Calculate(ByVal firstOperand As Double, ByVal secondOperand As Double, _
ByVal op As String) As Double
Select Case op
Case "+"
Return (firstOperand + secondOperand)
Case "-"
Return (firstOperand - secondOperand)
Case "X"
Return (firstOperand * secondOperand)
Case "/"
Return (firstOperand / secondOperand)
Case "\"
End Select
End Function
End Classenter code here

Operand 2 has to be the error-field, you just check if the first operand is 0
change
"ElseIf (operand1 = 0 And op = "/") Then
to ElseIf (operand2 = 0 And op = "/") Then
Give it a try :)

Related

vb google maps specific location

Imports System.Windows.Threading
Imports System.Threading
Imports System.Net
Imports System.Drawing
Imports System.IO
Imports Microsoft.Win32
Class Window1
#Region "Fields"
Private geoDoc As XDocument
Private location As String
Private zoom As Integer
Private saveDialog As New SaveFileDialog
Private mapType As String
Private lat As Double
Private lng As Double
#End Region
Private Sub GetGeocodeData()
Dim geocodeURL As String = "http://maps.googleapis.com/maps/api/" & _
"geocode/xml?address=" & location & "&sensor=false"
Try
geoDoc = XDocument.Load(geocodeURL)
Catch ex As WebException
Me.Dispatcher.BeginInvoke(New ThreadStart(AddressOf HideProgressBar), _
DispatcherPriority.Normal, Nothing)
MessageBox.Show("Ensure that internet connection is available.", _
"Map App", MessageBoxButton.OK, MessageBoxImage.Error)
Exit Sub
End Try
Me.Dispatcher.BeginInvoke(New ThreadStart(AddressOf ShowGeocodeData), _
DispatcherPriority.Normal, Nothing)
End Sub
Private Sub ShowGeocodeData()
Dim responseStatus = geoDoc...<status>.Single.Value()
If (responseStatus = "OK") Then
Dim formattedAddress = geoDoc...<formatted_address>(0).Value()
Dim latitude = geoDoc...<location>(0).Element("lat").Value()
Dim longitude = geoDoc...<location>(0).Element("lng").Value()
Dim locationType = geoDoc...<location_type>(0).Value()
AddressTxtBlck.Text = formattedAddress
LatitudeTxtBlck.Text = latitude
LongitudeTxtBlck.Text = longitude
Select Case locationType
Case "APPROXIMATE"
AccuracyTxtBlck.Text = "Approximate"
Case "ROOFTOP"
AccuracyTxtBlck.Text = "Precise"
Case Else
AccuracyTxtBlck.Text = "Approximate"
End Select
lat = Double.Parse(latitude)
lng = Double.Parse(longitude)
If (SaveButton.IsEnabled = False) Then
SaveButton.IsEnabled = True
RoadmapToggleButton.IsEnabled = True
TerrainToggleButton.IsEnabled = True
End If
ElseIf (responseStatus = "ZERO_RESULTS") Then
MessageBox.Show("Unable to show results for: " & vbCrLf & _
location, "Unknown Location", MessageBoxButton.OK, _
MessageBoxImage.Information)
DisplayXXXXXXs()
AddressTxtBox.SelectAll()
End If
ShowMapButton.IsEnabled = True
ZoomInButton.IsEnabled = True
ZoomOutButton.IsEnabled = True
MapProgressBar.Visibility = Windows.Visibility.Hidden
End Sub
' Get and display map image in Image ctrl.
Private Sub ShowMapImage()
Dim bmpImage As New BitmapImage()
Dim mapURL As String = "http://maps.googleapis.com/maps/api/staticmap?" & _
"size=500x400&markers=size:mid%7Ccolor:red%7C" & _
location & "&zoom=" & zoom & "&maptype=" & mapType & "&sensor=false"
bmpImage.BeginInit()
bmpImage.UriSource = New Uri(mapURL)
bmpImage.EndInit()
MapImage.Source = bmpImage
End Sub
Private Sub ShowMapUsingLatLng()
Dim bmpImage As New BitmapImage()
Dim mapURL As String = "http://maps.googleapis.com/maps/api/staticmap?" & _
"center=" & lat & "," & lng & "&" & _
"size=500x400&markers=size:mid%7Ccolor:red%7C" & _
location & "&zoom=" & zoom & "&maptype=" & mapType & "&sensor=false"
bmpImage.BeginInit()
bmpImage.UriSource = New Uri(mapURL)
bmpImage.EndInit()
MapImage.Source = bmpImage
End Sub
' Zoom-in on map.
Private Sub ZoomIn()
If (zoom < 21) Then
zoom += 1
ShowMapUsingLatLng()
If (ZoomOutButton.IsEnabled = False) Then
ZoomOutButton.IsEnabled = True
End If
Else
ZoomInButton.IsEnabled = False
End If
End Sub
' Zoom-out on map.
Private Sub ZoomOut()
If (zoom > 0) Then
zoom -= 1
ShowMapUsingLatLng()
If (ZoomInButton.IsEnabled = False) Then
ZoomInButton.IsEnabled = True
End If
Else
ZoomOutButton.IsEnabled = False
End If
End Sub
Private Sub SaveMap()
Dim mapURL As String = "http://maps.googleapis.com/maps/api/staticmap?" & _
"center=" & lat & "," & lng & "&" & _
"size=500x400&markers=size:mid%7Ccolor:red%7C" & _
location & "&zoom=" & zoom & "&maptype=" & mapType & "&sensor=false"
Dim webClient As New WebClient()
Try
Dim imageBytes() As Byte = webClient.DownloadData(mapURL)
Using ms As New MemoryStream(imageBytes)
Image.FromStream(ms).Save(saveDialog.FileName, Imaging.ImageFormat.Png)
End Using
Catch ex As WebException
MessageBox.Show("Unable to save map. Ensure that you are" & _
" connected to the internet.", "Error!", _
MessageBoxButton.OK, MessageBoxImage.Stop)
Exit Sub
End Try
End Sub
Private Sub MoveUp()
' Default zoom is 15 and at this level changing
' the center point is done by 0.003 degrees.
' Shifting the center point is done by higher values
' at zoom levels less than 15.
Dim diff As Double
Dim shift As Double
' Use 88 to avoid values beyond 90 degrees of lat.
If (lat < 88) Then
If (zoom = 15) Then
lat += 0.003
ElseIf (zoom > 15) Then
diff = zoom - 15
shift = ((15 - diff) * 0.003) / 15
lat += shift
Else
diff = 15 - zoom
shift = ((15 + diff) * 0.003) / 15
lat += shift
End If
ShowMapUsingLatLng()
Else
lat = 90
End If
End Sub
Private Sub MoveDown()
Dim diff As Double
Dim shift As Double
If (lat > -88) Then
If (zoom = 15) Then
lat -= 0.003
ElseIf (zoom > 15) Then
diff = zoom - 15
shift = ((15 - diff) * 0.003) / 15
lat -= shift
Else
diff = 15 - zoom
shift = ((15 + diff) * 0.003) / 15
lat -= shift
End If
ShowMapUsingLatLng()
Else
lat = -90
End If
End Sub
Private Sub MoveLeft()
Dim diff As Double
Dim shift As Double
' Use -178 to avoid negative values below -180.
If (lng > -178) Then
If (zoom = 15) Then
lng -= 0.003
ElseIf (zoom > 15) Then
diff = zoom - 15
shift = ((15 - diff) * 0.003) / 15
lng -= shift
Else
diff = 15 - zoom
shift = ((15 + diff) * 0.003) / 15
lng -= shift
End If
ShowMapUsingLatLng()
Else
lng = 180
End If
End Sub
Private Sub MoveRight()
Dim diff As Double
Dim shift As Double
If (lng < 178) Then
If (zoom = 15) Then
lng += 0.003
ElseIf (zoom > 15) Then
diff = zoom - 15
shift = ((15 - diff) * 0.003) / 15
lng += shift
Else
diff = 15 - zoom
shift = ((15 + diff) * 0.003) / 15
lng += shift
End If
ShowMapUsingLatLng()
Else
lng = -180
End If
End Sub
Private Sub DisplayXXXXXXs()
AddressTxtBlck.Text = "XXXXXXXXX, XXXXX, XXXXXX"
LatitudeTxtBlck.Text = "XXXXXXXXXX"
LongitudeTxtBlck.Text = "XXXXXXXXXX"
AccuracyTxtBlck.Text = "XXXXXXXXX"
End Sub
Private Sub HideProgressBar()
MapProgressBar.Visibility = Windows.Visibility.Hidden
ShowMapButton.IsEnabled = True
End Sub
' ShowMapButton click event handler.
Private Sub ShowMapButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ShowMapButton.Click
If (AddressTxtBox.Text <> String.Empty) Then
location = AddressTxtBox.Text.Replace(" ", "+")
zoom = 15
mapType = "roadmap"
Dim geoThread As New Thread(AddressOf GetGeocodeData)
geoThread.Start()
ShowMapImage()
AddressTxtBox.SelectAll()
ShowMapButton.IsEnabled = False
MapProgressBar.Visibility = Windows.Visibility.Visible
If (RoadmapToggleButton.IsChecked = False) Then
RoadmapToggleButton.IsChecked = True
TerrainToggleButton.IsChecked = False
End If
Else
MessageBox.Show("Enter location address.", _
"Map App", MessageBoxButton.OK, MessageBoxImage.Exclamation)
AddressTxtBox.Focus()
End If
End Sub
' SaveFileDialog FileOk event handler.
Private Sub saveDialog_FileOk(ByVal sender As Object, ByVal e As EventArgs)
Dim td As New Thread(AddressOf SaveMap)
td.Start()
End Sub
' ZoomInButton click event handler.
Private Sub ZoomInButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ZoomInButton.Click
ZoomIn()
End Sub
' ZoomOutButton click event handler.
Private Sub ZoomOutButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ZoomOutButton.Click
ZoomOut()
End Sub
' SaveButton click event handler.
Private Sub SaveButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles SaveButton.Click
saveDialog.ShowDialog()
End Sub
' RoadmapToggleButton Checked event handler.
Private Sub RoadmapToggleButton_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles RoadmapToggleButton.Checked
If (mapType <> "roadmap") Then
mapType = "roadmap"
ShowMapUsingLatLng()
TerrainToggleButton.IsChecked = False
End If
End Sub
' TerrainToggleButton Checked event handler.
Private Sub TerrainToggleButton_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles TerrainToggleButton.Checked
If (mapType <> "terrain") Then
mapType = "terrain"
ShowMapUsingLatLng()
RoadmapToggleButton.IsChecked = False
End If
End Sub
Private Sub MapImage_MouseLeftButtonUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles MapImage.MouseLeftButtonUp
If (location IsNot Nothing) Then
Dim gMapURL As String = "http://maps.google.com/maps?q=" & location
Process.Start("IExplore.exe", gMapURL)
End If
End Sub
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
AddressTxtBox.Focus()
With saveDialog
.DefaultExt = "png"
.Title = "Save Map Image"
.OverwritePrompt = True
.Filter = "(*.png)|*.png"
End With
AddHandler saveDialog.FileOk, AddressOf saveDialog_FileOk
End Sub
Private Sub MinimizeButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MinimizeButton.Click
Me.WindowState = Windows.WindowState.Minimized
End Sub
Private Sub CloseButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles CloseButton.Click
Me.Close()
End Sub
//ds
Private Sub BgndRectangle_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles BgndRectangle.MouseLeftButtonDown
Me.DragMove()
End Sub
//df
Private Sub MoveUpButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MoveUpButton.Click
MoveUp()
End Sub
//sdf
Private Sub MoveDownButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MoveDownButton.Click
MoveDown()
End Sub
Private Sub MoveLeftButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MoveLeftButton.Click
MoveLeft()
End Sub
Private Sub MoveRightButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MoveRightButton.Click
MoveRight()
End Sub
End Class
i have this class for searching through google maps.
how can i pass it a location so that on startup it can show the given location on the map?
The WPF form has a loaded event, you can add some code there to load your first map:
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
ShowMapButton_Click(sender, e)
End Sub
In this case I hardcoded an address into the AddressTxtBox and called Show Map. You can add whatever code you need to set up the conditions for the first map.
If the question is "How do I pass information to a form to be used when it first load" that is a much shorter post!
I don't work a lot with WPF so I'm not up on naming conventions and best practices so keep that in mind... For example the called form would not be called MainWindow!
In Winforms a method like this could be used:
Public in_StartAddress As String = ""
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
If in_StartAddress.Length > 0 Then AddressTxtBox.Text = in_StartAddress
ShowMapButton_Click(sender, e)
End Sub
' calling routine on another form
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim frm As New MainWindow
frm.in_StartAddress = "1600 Pensylvania Ave, Washington DC"
frm.Show()
frm = Nothing
End Sub
Look for posts on passing parameters to new forms/windows.

I'm doing a VB.net Caesar Cipher

Good day,
i'm having trouble of finishing this homework :<
i'm doing a caesar cipher where the user will have a txt file
then the program will find the text file and read what's inside of it
then overwrite the text file
so far i'm able to do the code but i'm getting a
index out of range and nullreference exception
here's my code
Imports System.IO
Public Class main_form
Dim x, y, z, str_len As Integer 'where x is a counter for the array
Dim loc, read(5), write(), str_1, str_2, aa As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub brw_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles brw_btn.Click
TextBox1.Clear()
OFD1.ShowDialog()
TextBox1.Text = OFD1.FileName
loc = OFD1.FileName
read = File.ReadAllLines(OFD1.FileName)
End Sub
Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
'Formula of Caesar's Cipher
z = 1
x = 0
If read(x) <> "" Then
While read(x) <> ""
str_2 = ""
str_1 = read(x)
str_len = Len(str_1)
MessageBox.Show(str_2)
For i As Integer = 0 To str_len - 1
y = Asc(Mid(str_1, i + 1, i + 2))
y = y + Val(TextBox2.Text)
str_2 = str_2 + Chr(y)
MessageBox.Show(str_2)
Next
MessageBox.Show(str_2)
write(x) = str_2
File.AppendAllLines(OFD1.FileName, write(x))
x += 1
End While
Else
End If
End Sub
End Class
Thanks!
Of course you are getting out of range exception because :
While read(x) <> ""
...
...
x += 1 'if x goes out of range the next loop in while will access read(x <-out of range)
End While
You have to insert
While read(x) <> ""
...
...
x += 1
If x >= read.Length
Exit While
End If
End While
Also:
Dim write() as String
...
write(x) = str_2 '<-write is used un initialized, null reference exception
Change write() to write or:
Private Sub enc_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enc_btn.Click
ReDim write(read.Length) '<---
z = 1
x = 0
If read(x) <> "" Then
...
...
Valter

Visual Basic - Adding two binary numbers

Hi im new on here and in coding in general. I've been working on this code for adding two binary numbers together, individually the parts work but combined the don't. If anyone could help me with a solution for this I would be very grateful. Also if it could be shortened that would help as well, Thanks.
Class Form1
Dim intNum1 As Integer
Dim intNum2 As Integer
Dim intNum3 As Integer
Public Function BinaryToDecimalA(ByRef Binary As String) As Integer
Dim BinaryNumA As Integer
Dim BitCountA As Short
For BitCountA = 1 To Len(Binary)
BinaryNumA = BinaryNumA + (CDbl(Mid(Binary, Len(Binary) - BitCountA + 1, 1)) * (2 ^ (BitCountA - 1)))
Next BitCountA
BinaryToDecimalA = BinaryNumA
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = (BinaryToDecimal((TextBox1.Text)))
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox1.MaxLength = 3
End Sub
Public Function BinaryToDecimal(ByRef Binary As String) As Integer
Dim BinaryNum As Integer
Dim BitCount As Short
For BitCount = 1 To Len(Binary)
BinaryNum = BinaryNum + (CDbl(Mid(Binary, Len(Binary) - BitCount + 1, 1)) * (2 ^ (BitCount - 1)))
Next BitCount
BinaryToDecimal = BinaryNum
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum2 = (BinaryToDecimal((TextBox2.Text)))
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox2.MaxLength = 3
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = Integer.Parse(TextBox1.Text)
intNum2 = Integer.Parse(TextBox2.Text)
intNum3 = intNum1 + intNum2
End Sub
Private Sub intNum3_TextChanged(sender As Object, e As EventArgs) Handles TextBoxAns.TextChanged
Dim i As Long, x As Long, bin As String
Const maxpower = 7
TextBoxAns.Enabled = False
bin = ""
x = Val(intNum3)
If x > 2 ^ maxpower Then
MsgBox("Number must be no longer than " & Str$(2 ^ maxpower))
TextBoxAns.Text = ""
End If
If x < 0 Then bin = bin + "1" Else bin = bin + "0"
For i = maxpower To 0 Step -1
If x And (2 ^ i) Then
bin = bin + "1"
Else
bin = bin + "0"
End If
Next
TextBoxAns.Text = bin
End Sub
End Class
This should work -
Not my code (reference http://www.bigresource.com/VB-Converting-a-number-to-its-binary-number-uDbSei3kPM.html) but it works !
Public Function BinaryAddition(ByVal A As String, ByVal B As String) As String
Dim curA As Currency
Dim curB As Currency
Dim curResult As Currency
curA = BinToDec(A)
curB = BinToDec(B)
curResult = (curA + curB) ' Mod (2 ^ 32)
BinaryAddition = DecToBin(curResult)
End Function
Private Function DecToBin(curDec As Currency) As String
Dim strTemp As String
Dim i As Integer
i = 31
Do While i >= 0
If curDec >= (2 ^ i) Then
strTemp = strTemp & "1"
curDec = curDec - (2 ^ i)
Else
strTemp = strTemp & "0"
End If
i = i - 1
Loop
DecToBin = strTemp
End Function
Module Module1
Sub Main()
Console.WriteLine("Enter the first binary number, then enter the second binary number")
Dim num As Integer = Convert.ToInt32(Console.ReadLine, 2)
Console.WriteLine(Convert.ToString(num + Convert.ToInt32(Console.ReadLine, 2), 2))
Console.ReadLine()
End Sub
End Module

not accessible in this context because it is 'Private' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm writing some code for a calculator and I keep getting this error. I have the math functions in another class but the variables from form1 are not accessible. Below is my code.
I've also tried changing my Dim variables to public but that also doesn't work.
Public Class Form1
'create a value to keep track of whether the calculation is complete so the calculator can revert to zero for new calculations
Dim state As Integer
'create values to store information on numbers and signs entered as well as the answer returned
Dim one As Double
Dim two As Double
Dim ans As Double
Dim sign As Char
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'when "Return" or "Enter" Key is selected button 15 is clicked (seems to only work when textbox selected????)
Me.AcceptButton = Button15
'change the title of the form
Me.Text = "Simple Calculator"
'label the buttons logically
Button1.Text = "1"
Button2.Text = "2"
Button3.Text = "3"
Button4.Text = "4"
Button5.Text = "5"
Button6.Text = "6"
Button7.Text = "7"
Button8.Text = "8"
Button9.Text = "9"
Button10.Text = "0"
Button11.Text = "+"
Button12.Text = "-"
Button13.Text = "X"
Button14.Text = "/"
Button15.Text = "Calc"
Button16.Text = "About Me"
Button17.Text = "Clear"
'allows form to revcieve key events
Me.KeyPreview = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'create action when button 1 is clicked
'if state is 1 then previous calculation was solved, then clear textbox to allow for new input
If state = 1 Then
TextBox1.Text = ""
'insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
'return state of calculator to zero to designate that calculation has NOT been solved
state = 0
Else
'else insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
End If
End Sub
' the above function for each numbered button
Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
state = 0
Else
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
state = 0
Else
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
state = 0
Else
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
End If
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
state = 0
Else
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
End If
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
state = 0
Else
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
End If
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
state = 0
Else
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
End If
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
state = 0
Else
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
End If
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
state = 0
Else
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
End If
End Sub
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
state = 0
Else
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
End If
End Sub
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
'create an action for when addition button is clicked
Try
'when button is clicked dim sign and text in textbox
sign = "+"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
'repeat the above action for remainder of arithmic functions
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Try
'when button is clicked dim sign and text in textbox
sign = "-"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Try
sign = "*"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Try
sign = "/"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
'run functions based on sign stored during calculation
Try
two = TextBox1.Text
If sign = "+" Then
Calculator2.Math.add()
ElseIf sign = "-" Then
Calculator2.Math.minus()
ElseIf sign = "*" Then
Calculator2.Math.multiply()
ElseIf sign = "/" Then
Calculator2.Math.divide()
End If
'if user attempts to divide by zero return divide by zero error in textbox
If TextBox1.Text = "Infinity" Then
TextBox1.Text = "Divide by Zero Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End If
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
'create message box that provides information about author
Dim msg = "Student Name: Emily Wong" & vbCrLf & "Student Number: 0692740" ' Define the message you want to see inside the message box.
Dim title = "About Me" ' Define a title for the message box.
Dim style = MsgBoxStyle.OkOnly ' make an ok button for the msg box
Dim response = MsgBox(msg, style, title)
End Sub
Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
'create a clear button to clear textboxes when clicked and reset state of calculator
TextBox1.Text = ""
state = 0
End Sub
And this is my other class
Public Class Math
Inherits Form1
'create funtions for add,sub, multiply, and divide features
Sub add()
ans = one + two 'creates calculation of the entered numbers
TextBox1.Text = ans 'returns answer into the textbox
state = 1 'returns state to 1 to show that calculation has occured
End Sub
Sub minus()
ans = one - two
TextBox1.Text = ans
state = 1
End Sub
Sub multiply()
ans = one * two
TextBox1.Text = ans
state = 1
End Sub
Sub divide()
ans = one / two
TextBox1.Text = ans
state = 1
End Sub
End Class
state is a private variable in Form1. You can't access from code outside of Form1. Your Math class cannot reference state. Remove the calls to state from the Math class code. An outside class should not be changing the state of another object in anycase.
Try this instead:
Public Class accounting
Dim Operand1 As Double
Dim Operand2 As Double
Dim [Operator] As String
These are the button from 1 - 0
Private Sub Button6_Click_1(sender As Object, e As EventArgs) Handles Button9.Click, Button8.Click, Button7.Click, Button6.Click, Button5.Click, Button4.Click, Button19.Click, Button12.Click, Button11.Click, Button10.Click
txtans.Text = txtans.Text & sender.text
End Sub
This button is for period/point
Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
If InStr(txtans.Text, ".") > 0 Then
Exit Sub
Else
txtans.Text = txtans.Text & "."
End If
End Sub
This button is for clear or "C" in calculator
Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
txtans.Text = ""
End Sub
These are for add,subtract,divide, and multiply
Private Sub Buttonadd_Click(sender As Object, e As EventArgs) Handles Button13.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "+"
End Sub
Private Sub Buttondivide_Click(sender As Object, e As EventArgs) Handles Button15.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "-"
End Sub
Private Sub Buttonsubtract_Click(sender As Object, e As EventArgs) Handles Button16.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "*"
End Sub
Private Sub Buttonmultiply_Click(sender As Object, e As EventArgs) Handles Button14.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "/"
End Sub
This button is for "=" sign
Private Sub Buttoneequal_Click(sender As Object, e As EventArgs) Handles Button17.Click
Dim Result As Double
Operand2 = Val(txtans.Text)
'If [Operator] = "+" Then
' Result = Operand1 + Operand2
'ElseIf [Operator] = "-" Then
' Result = Operand1 - Operand2
'ElseIf [Operator] = "/" Then
' Result = Operand1 / Operand2
'ElseIf [Operator] = "*" Then
' Result = Operand1 * Operand2
'End If
Select Case [Operator]
Case "+"
Result = Operand1 + Operand2
txtans.Text = Result.ToString("#,###.00")
Case "-"
Result = Operand1 - Operand2
txtans.Text = Result.ToString("#,###.00")
Case "/"
Result = Operand1 / Operand2
txtans.Text = Result.ToString("#,###.00")
Case "*"
Result = Operand1 * Operand2
txtans.Text = Result.ToString("#,###.00")
End Select
txtans.Text = Result.ToString("#,###.00")
End Sub
This button is for backspace effect.
Private Sub Buttondel_Click(sender As Object, e As EventArgs) Handles Button21.Click
If txtans.Text < " " Then
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1 + 1)
Else
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1)
End If
End Sub
Note that "txtans.text" is the textbox where the user inputs and where the output shows.

The button.BackColor statement seem to be executed, but no colour change is show

I'm trying to re-create the classic game "Simon" for a project. The code I have here should hopefully create a random number, translate that to a colour change for a random button, wait a short time, and then do the same for another random button. I can't spot any problems, but on execution the buttons remain uchanged.
Public Class MenuForm
Dim failure As Boolean
Dim pattern() As Integer
Dim maincounter As Integer = 1
Dim diff As Integer
Dim sender As Object
Dim e As EventArgs
Dim timewaited As Integer
Dim timefinished As Boolean
Private Sub Menuform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get the difficulty level from the player
Dim InputtedDifficulty As Integer = InputBox("Please enter difficulty. 1-Easy 2-Medium 3-Hard")
'Validate difficulty choice
Do While InputtedDifficulty > 3 Or InputtedDifficulty < 1
InputtedDifficulty = InputBox("Input incorrect. Please re-enter selection. 1-Easy 2-Medium 3-Hard")
Loop
'Set speed of blinking based on difficulty choice
Select Case InputtedDifficulty
Case 1
diff = 1000
Case 2
diff = 500
Case 3
diff = 20
End Select
End Sub
Private Sub run_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles run.Click
Call GameController()
End Sub
Private Sub GameController()
Dim buttonRepeater As Integer
'Call checkFail()
Do While failure = False
maincounter = maincounter + 1
Call Pattern_creator(sender, e)
For buttonRepeater = 1 To maincounter
Call button_controller(sender, e)
timewaited = 0
timefinished = False
ButtonTimer.Enabled = True
If timefinished = True Then
End If
Button1.BackColor = Color.Blue
Button2.BackColor = Color.Blue
Button3.BackColor = Color.Blue
Button4.BackColor = Color.Blue
Next buttonRepeater
Loop
End Sub
Private Sub Pattern_creator(ByVal sender As System.Object, ByVal e As System.EventArgs)
ReDim Preserve pattern(maincounter)
Randomize()
pattern(maincounter) = Int((Rnd() * 4) + 1)
ReDim Preserve pattern(maincounter + 1)
End Sub
Private Sub button_controller(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Ths case statement takes the random number generated earlier and translates that to
'a button flash
Select Case pattern(maincounter)
Case 1
Button1.BackColor = Color.Red
Case 2
Button2.BackColor = Color.Red
Case 3
Button3.BackColor = Color.Red
Case 4
Button4.BackColor = Color.Red
End Select
End Sub
Private Sub ButtonTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTimer.Tick
If timewaited = 5 Then
ButtonTimer.Enabled = False
timefinished = True
Else
timewaited = timewaited + 1
End If
End Sub
End Class
Any help would be very much appreciated, I've been staring at this for ages with no progress.