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
Related
I am making a Math quiz game and I wondering why the question does not change to a NEW ONE when I get the right answer and HOW to make it to 10 and stop running then jump out a message box to ask the user want to PLAY AGAIN or not?
Public Class Multiplication
Dim TotalQuestion As Integer
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim numOne As Integer = R.Next(0, 10)
Dim numTwo As Integer = R.Next(1, 10)
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = numOne & " x " & numTwo & " = "
lblQuestionMUL.Text = Show
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Return num1 * num2
Generate()
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, numOne & numTwo)
Ans = Multiply(numOne, numTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
Generate()
End Sub
End Class
In addition to previous comments you should set the numOne and numTwo variables to random numbers in Generate Sub (Keeping the declaration as Global Variables). Your code just set them in the beginning to random numbers only once. Check the code below:
Public Class Multiplication
Dim TotalQuestion As Integer = 0
Dim CorrectAnswer As Integer
Dim WrongAnswer As Integer
Dim R As New Random
Dim NumOne As Integer
Dim NumTwo As Integer
Dim QuizCompleted As Boolean = False
Dim Ans As Integer = 0
Dim Tries As Integer = 0
Private Sub Multiplication_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Generate()
End Sub
Sub Generate()
If TotalQuestion < 10 Then
NumOne = R.Next(0, 10)
NumTwo = R.Next(1, 10)
TotalQuestion = TotalQuestion + 1
Dim Show As String
Show = NumOne & " x " & NumTwo & " = "
lblQuestionMUL.Text = Show
Else
QuizCompleted = True
End If
End Sub
Private Function Multiply(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
Generate()
Return num1 * num2
End Function
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Integer.TryParse(lblQuestionMUL.Text, NumOne & NumTwo)
Ans = Multiply(NumOne, NumTwo)
If Val(txtAnswer.Text) = Ans Then
CorrectAnswer = CorrectAnswer + 1
Else
WrongAnswer = WrongAnswer + 1
End If
lblCorrectAns.Text = CorrectAnswer
lblWrongAns.Text = WrongAnswer
txtAnswer.Clear()
txtAnswer.Focus()
If QuizCompleted Then
MsgBox("Quiz Completed")
End If
End Sub
End Class
I have data like this
date value
24sep2014 2:23:01 0.1
24sep2014 2:23:02 0.3
24sep2014 2:23:03 0.2
24sep2014 2:23:04 0.3
These are not coma seprated value. I wanted to write in CSV file. Apend the value for next row.
1)How to open file only once here. when it run next time file name has to change to other name
2) How to append the next values
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim myPort As Array
Dim Distance As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(myPort)
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Chart1.Series.Clear()
Chart1.Titles.Add("Demo")
'Create a new series and add data points to it.
Dim s As New Series
s.Name = "CURRENT"
s.ChartType = SeriesChartType.Line
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = BaudComboBox.Text
SerialPort1.Open()
Timer1.Start()
Timer2.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim counter As Integer
counter = 0
Try
SerialPort1.Write("c")
System.Threading.Thread.Sleep(250)
Dim k As Double
Dim distance As String = SerialPort1.ReadLine()
k = CDbl(distance)
ListBoxSensor.Text = k
Dim s As New Series
s.Points.AddXY(1000, k)
Chart1.Series.Add(s)
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile)) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Catch ex As Exception
End Try
End Sub
Private Sub Relay_ON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_ON.Click
SerialPort1.Write("1")
End Sub
Private Sub Relay_Off_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_Off.Click
SerialPort1.Write("0")
End Sub
End Class
Here i am opening file again and again. that reason i can store only one value
# steve error
The second parameter of OpenTextFileWriter allows to append instead of overwrite your file.
So it is simply a matter to check if the file exists (so you insert the header names) and then write your data
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Notice the Using Statement to be sure to close and dispose the file resource also in case of exceptions.
However given the simple text that need to be written you could also choose to use the method WriteAllText
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current" & Environment.NewLine
End If
Dim y As String = DateAndTime.Now
Dim x As String = headerText & y & "," + distance & Environment.NewLine
My.Computer.FileSystem.WriteAllText(csvFile, x, True)
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
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 :)
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.