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
Related
Private Sub Btn_Cast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Cast.Click
Dim Counter As Integer = 0
If ChkBox_Barton.CheckState = 1 And ChkBox_Martin.CheckState = 1 And ChkBox_Richards.CheckState = 1 Then
MsgBox("Don't vote for more than 2")
End If
Dim Count_Barton As Integer
Dim Count_Martin As Integer
Dim Count_Richards As Integer
If ChkBox_Barton.Checked Then Count_Barton += 1
If ChkBox_Martin.Checked = 1 Then Count_Martin += 1
If ChkBox_Richards.CheckState = 1 Then Count_Richards += 1
End Sub
Problem is, I'm trying to count it everytime, then let it reset and count again.
Example. I select Barton one time, click vote, then i should be able to select someone new and click vote and it should keep counting.
what can I do?
I need to then display my results. Should I just hold the number in a text or Integer file then display it that way?
I quickly set up your application myself.
Following Code applies to this GUI:
Code:
Public Class VoteCounter
Dim intCountBarton As Integer
Dim intCountMartin As Integer
Dim intCountRichards As Integer
Private Sub ButtonVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonVote.Click
If CheckBoxBarton.CheckState = 1 And CheckBoxMartin.CheckState = 1 And CheckBoxRichards.CheckState = 1 Then
MsgBox("Don't vote for more than 2")
CheckBoxBarton.Checked = False
CheckBoxMartin.Checked = False
CheckBoxRichards.Checked = False
End If
If CheckBoxBarton.Checked Then
intCountBarton += 1
End If
If CheckBoxMartin.Checked Then
intCountMartin = intCountMartin + 1
End If
If CheckBoxRichards.Checked Then
intCountRichards = intCountRichards + 1
End If
CheckBoxBarton.Checked = False
CheckBoxMartin.Checked = False
CheckBoxRichards.Checked = False
End Sub
Private Sub ButtonResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonResult.Click
MsgBox("Barton: " & intCountBarton & vbNewLine & "Martin: " & intCountMartin & vbNewLine & "Richards: " & intCountRichards)
End Sub
Private Sub ButtonReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReset.Click
CheckBoxBarton.Checked = False
CheckBoxMartin.Checked = False
CheckBoxRichards.Checked = False
intCountBarton = 0
intCountMartin = 0
intCountRichards = 0
End Sub
End Class
Dim Count_Barton As Integer = 0
Dim Count_Martin As Integer = 0
Dim Count_Richards As Integer = 0
Private Sub Btn_Cast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Cast.Click
Dim Counter As Integer = 0 'NOT SURE WHAT THIS IS DOING... NOT BEING USED
If ChkBox_Barton.CheckState = 1 And ChkBox_Martin.CheckState = 1 And ChkBox_Richards.CheckState = 1 Then
MsgBox("Don't vote for more than 2")
Else
If ChkBox_Barton.Checked Then Count_Barton += 1
If ChkBox_Martin.Checked = 1 Then Count_Martin += 1
If ChkBox_Richards.CheckState = 1 Then Count_Richards += 1
End If
End Sub
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)
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
The code below runs and keeps repeating over and over again. I only pasted the up_timer but others do the same. Any ideas on how to make it run once, then repeat to the random loop and so on?
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Application.DoEvents()
Randomize()
Dim value As Integer = CInt(Int((4 * Rnd()) + 1))
If value = 1 Then
MsgBox("Up")
up.Start()
ElseIf value = 2 Then
MsgBox("Down")
down.Start()
ElseIf value = 3 Then
MsgBox("Left")
left.Start()
ElseIf value = 4 Then
MsgBox("Right")
right.Start()
End If
Timer1.Stop()
End Sub
Private Sub up_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up.Tick
Static moveCount As Integer = 1
If Me.mob2.Location.Y > 12 Then
Me.mob2.Location = New Point(Me.mob2.Location.X, Me.mob2.Location.Y - 5)
End If
moveCount += 1
If moveCount = 10 Then
moveCount = 1
Me.Timer1.Start()
Me.up.Stop()
End If
End Sub
Looks like this is what you need, based on your complaint that timer1 repeats same numbers
Dim rand1 As New Random(CInt(Date.Now.Ticks And &h0000FFFF))
Dim value As Integer = rand1.Next(1, 4)
This will not repeat
Plus, you have to move Timer1.Stop() to beginning of the method
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.