I have to do a program in Visual Basic that displays the status of 100 lockers being either open or closed using a Boolean array. When the button Initialize is clicked, all the lockers should have a status of opened, but when Simulate is clicked, it goes through a process of closing every Nth locker (every 2nd locker, then every 3rd locker, then every 4th locker, and so on).
I have it working so that it always displays opened for every locker, but I can't figure out how to make it close every Nth locker.
Here is my code:
Public Class Form1
Dim index As Integer
Dim doors(100) As Boolean
Private Sub btnInitialize_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInitialize.Click
Dim count As Integer
lstLockers.Items.Clear()
lstLockers.Items.Add("Locker" & vbTab & "Status")
For count = 1 To 100
doors(count) = True
If doors(count) = True Then
lstLockers.Items.Add(count & vbTab & "Opened")
End If
Next
End Sub
Private Sub btnSimulate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSimulate.Click
lstLockers.Items.Clear()
lstLockers.Items.Add("Locker" & vbTab & "Status")
Dim count As Integer
Dim eq As Integer
For count = 1 To 100
doors(count) = True
If doors(count) = True Then
lstLockers.Items.Add(count & vbTab & "Opened")
ElseIf doors(count) = False Then
lstLockers.Items.Add(count & vbTab & "Closed")
End If
Next
End Sub
End Class
In your btnSimulate_Click method, you are setting doors index to true and then immediately checking if it is true or not. This is why it always says opened.
Regarding closing every Nth locker, you can do this with a simple counter variable.
' n represents the "Nth" locker to close.
Dim n As Integer = 2
Dim progress As Integer = 0 ' Progress to n.
For count = 1 To 100
' This line shouldn't be here. doors has already been initialized.
'doors(count) = True
' Increment progress towards n.
progress = progress + 1
' Check if Nth interval is reached.
If n = progress Then
' It is. Close the locker.
doors(count) = False
' Increment n and reset the progress counter.
n = n + 1
progress = 0
End If
If doors(count) = True Then
lstLockers.Items.Add(count & vbTab & "Opened")
ElseIf doors(count) = False Then
lstLockers.Items.Add(count & vbTab & "Closed")
End If
Next
This would close lockers:
2 (n = 2)
5 (n = 3)
9 (n = 4)
14 (n = 5)
etc.
Related
I am a new programmer learning Visual Basic.
Right now, I'm working on a project about a softball scoreboard. I have been working on this project for a bit, and I am confused on 1 thing.
The thing I am confused on is that I put in a messagebox that said invalid input for negative numbers, but it does not delete it from lstScores and even though the message box appears it still counts as a inning input.
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
This is the code:
Public Class frmSoftballScoreboard
Const VALID_MESSAGE As String = "Enter valid runs value"
Const ONLY_MESSAGE As String = "Only seven innings are allowed"
'Declaring array
Dim scores(6) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs : Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
'Clear Menu click
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
I would really appreciate it if you could help. Thank you.
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
Exit Sub
ElseIf runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
This is the reason why if you input invalid data it will add into lstScores, because your If statement.. is in bottom of your code, although is not recommend where you put the If else statement... Remember reading of the code is start in top to bottom.
Your first If statement is like this. If runs <> "" then ...., of course if you type the -1 value in the Input Text the Boolean will result to true, If -1 <> "" = true, then it will proceed to the statement which is
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
This is the line of code even the value is invalid or not it still adding value in the lstScores, lstScores.Items.Add(scores(i) & " :" & runningScore)
Now after that statement you will receive a message which is :
Enter valid runs value
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
That code is the reason why you receiving the message. If you input -1 of course the result of boolean is true, why? -1 is lessthan to 0 which is true.
The thing i do is, I've insert If statement.. above, which is If runs < 0 then .... and also Exit Sub to instantly end the statement. If you input -1 to Input Text the result is something like this, if runs(-1) lessthan to 0 the Boolean result is true then it will proceed to statement which is the Message and Exit Sub.
Try my code above, and also use Breakpoints.. Hope this helps..
Basically, I need 2 make a student number and after every new entry I put the student number should +1 so 20182(or 3 if male)001 will be 20182(or 3 if male)002 after I push the button and it must keep +1 but once it reaches the 10th registered student the format changes to 20182(3 if male)010.
I have done everything but make the number +1 every time I use the button
so basically the answer must be:
Student Number is 20182001
Surname , Name
contact details
but, I done everything besides the 001, 002,003 till 010 part so if anybody could help I would be thankful
Public Class Form1
Public Number As Integer = 2018000
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSurname As String
Dim strFullName As String
Dim strContact As String
Dim strGender As String
Dim x As Integer
'IF statement'
If Me.cboGender.SelectedItem = "Female" Then
Number = 2018300
Else
End If
If Me.cboGender.SelectedItem = "Male" Then
Number = 2018200
Else
End If
'Finding The Student Number'
Dim i As Integer = 0
Do While (i < 1)
i = i + 1
Loop
If i = 201820010 Then
Number = 201800
Else
If i = 201830010 Then
Number = 201800
End if
End If
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
End Class
Not sure what your code was doing, but based on your requirements:
Public baseFemale As Integer = 20182000
Public baseMale As Integer = 20183000
Public autoNumber As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number as Integer;
autoNumber = autoNumber + 1
If Me.cboGender.SelectedItem = "Female" Then
Number = baseFemale + autoNumber
Else
Number = baseMale + autoNumber
Else
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
Additionally you may want to check for autoNumber exceeding 999 - but I leave that as an exercise for you.
I have code that I have written, that has 3 labels for number of hurricanes, average hurricanes, and the year with the most hurricanes from a txt file. The code is working and the first 2 labels are displaying the correct results. However the last label is displaying the number of the year with the most hurricanes instead of the year.
Here is what I have:
Option Strict On
Public Class frmHurricaneStatistics
' Class level Private variables.
Public Shared _intSizeOfArray As Integer = 20
Private _strYears(_intSizeOfArray) As String
Private _intNumberOfHurricans(_intSizeOfArray) As Integer
Private Sub frmHurricaneStatistics_Load(sender As Object, e As EventArgs
) Handles MyBase.Load
' This load event reads the inventory text file and fills
' the ComboBox object with the Hurricane Statistics.
' Initialize an instace of the streamreader object and declare variables.
Dim objReader As IO.StreamReader
Dim strHurricaneStatistics As String = "Hurricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart the
application when the file is available."
' Verify the Hurricane.txt file exists.
If IO.File.Exists(strHurricaneStatistics) Then
objReader = IO.File.OpenText(strHurricaneStatistics)
' Read the file line by line until the file is completed.
Do While objReader.Peek <> -1
_strYears(intCount) = objReader.ReadLine()
_intNumberOfHurricans(intCount) = Convert.ToInt32(objReader.ReadLine())
intCount += 1
Loop
objReader.Close()
' The ComboBox objext is filled with the Years for Hurricanes.
For intFill = 0 To (_strYears.Length - 1)
cmbYears.Items.Add(_strYears(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Close()
' If ComboBox is filled then enable the Display Statistics button.
' btnDisplayStatistics.Enabled = True
End If
End Sub
Private Sub btnDisplayStatistics_Click(sender As Object, e As EventArgs
) Handles btnDisplayStatistics.Click
' This click event calls the sub procedures for the selected years and
' the number of hurricans in that year.
Dim intSelectedYear As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectAYearError As String = "Please Select a Year"
' If the ComboBox object has a selection, Display Statistics.
If cmbYears.SelectedIndex >= 0 Then
intSelectedYear = cmbYears.SelectedIndex
Else
MsgBox(strSelectAYearError, , strMissingSelection)
End If
' The procedure MakeLabelsVisible Is called to display the labels
' And the results.
MakeLabelsVisible()
Dim intAverage As Double
Dim intYear As Integer
For intIndex As Integer = 0 To _intNumberOfHurricans.Length - 1
If intYear < _intNumberOfHurricans(intIndex) Then
intYear = _intNumberOfHurricans(intIndex)
End If
intAverage = intAverage + _intNumberOfHurricans(intIndex)
Next
intAverage = intAverage / _intNumberOfHurricans.Length
' Display the statistics for the Storm Average in the selected Year
' and the most active year within the range of year.
lblNumberOfHurricanes.Text = "The Number of Hurricanes in the Year " &
_strYears(intSelectedYear) & " is " & _intNumberOfHurricans(intSelectedYear).ToString() & "."
lblAvergeNumberHurricanes.Text = "The Average Number of Storms was " & FormatNumber(intAverage, 0) & " Hurricanes."
lblMostStorms.Text = "The Year " & intYear & " Had The Most Storms Between " & (
_strYears(20) & " And " & (_strYears(0).ToString))
End Sub
Private Sub MakeLabelsVisible()
' This procedure displays the labels with the calculated results
lblNumberOfHurricanes.Visible = True
lblAvergeNumberHurricanes.Visible = True
lblMostStorms.Visible = True
End Sub
Updated code.
Looks like you're just populating intYear with the number of hurricanes?
intYear = _intNumberOfHurricans(intIndex)
I can't see where you're wanting to get a year value from. Does one even exist? Please post the rest of the code
Edit:
From what I understand (correct me if I'm wrong), you want the year that had the highest number of hurricanes? If so
Try
For intIndex As Integer = 0 To _intNumberOfHurricans.Length - 1
If _intNumberOfHurricans(intIndex) = _intNumberOfHurricans.Max Then
intYear = Integer.Parse(_strYears(intIndex))
End If
intAverage = intAverage + _intNumberOfHurricans(intIndex)
Next
What I'm doing here is looking for the highest value in _intNumberOfHurricans and comparing it to the number of hurricanes in the current iteration. If they're the same, then we are at the year with the highest number of hurricanes, so we populate intYear with _strYears(but as an Integer).
This code isn't perfect. For example, if the highest amount of hurricanes is 100, but there are 2 years where there are 100 hurricanes, it will only give the latest year, not the first year there were 100 hurricanes.
Because you set;
intYear = _intNumberOfHurricans(intIndex)
Not the year, number of hurricans. That should have point to a Year property.
intYear = _intNumberOfHurricans(intIndex).Year
Hope helps.
I seem to be having trouble with my program working and I am finding it hard to understand what I have done wrong, first of all I need a simple ( not really complicated) way of checking that the user cannot enter a string or a number over the requested amount (which currently is 1- 9 for menu options and 10 for a save option - which I need to do later) The code below is the code for the number and string checker relating to the menu and the code below the line is the whole code.
I have tried doing this but it just loops when you enter it for the row and lets you through whatever number you enter on the column. I need help also on other question relating to this like
Telling the user what ship they have hit,
Saving and Loading the game
And a score counter - I had this working then it got deleted when trying to fix first question
And a limit on the amount of goes they can have.
I will upload the code required tomorrow as cannot now, But if anybody has access to the AQA As Level free pseudocode that they give you - (its not illegal ! ) Please help me !
Sub GetRowColumn(ByRef Row As Integer, ByRef Column As Integer) ' Asks the user about where they want to go in the code
Console.WriteLine()
Dim checkcol, checkrow As String ' Defining the variables that I will user later
Dim AscCol, AscRow As Integer
Console.Write("Please enter a column:") ' Asks users to enter a column
checkcol = Console.ReadLine()
AscCol = Asc(checkcol(0)) ' It will check it on the ASCII scale to see if it isnt a letter
While AscCol > 57 Or AscCol < 48 ' If it doesnt fit in here, it is not one of the alloacated numbers
Console.WriteLine("This is not a number.")
Console.Write("Please enter a column")
checkcol = Console.ReadLine() ' Does the same for checkcol
AscCol = Asc(checkcol(0))
End While
checkcol = ((Chr(AscCol)))
Column = CInt(checkcol)
Console.WriteLine() ' This is a printed space for spacing when printed as a code
Do
If Column < 0 Or Column > 9 Then ' Now if it fits the column alloation e.g. 1 to 9 it will be allowed through
Console.WriteLine()
Console.WriteLine(" That is an invalid Input") ' Tell the user that they cannot go through as it doesn't fit the right requrirments
Column = Console.ReadLine()
End If
Console.WriteLine()
Loop Until Column < 10 And Column >= 0 ' This part of the code will run until their answer is under 10 and over 0
Console.Write("Please enter a row:") ' Here is same for rows as it is for columns
checkrow = Console.ReadLine()
AscRow = Asc(checkrow(0))
While AscRow > 57 Or AscRow < 48
Console.WriteLine("This is not a number.")
Console.Write("Please enter a row")
AscRow = Asc(checkrow(0))
End While
Row = CInt(checkrow)
Do
If Row < 0 Or Row > 9 Then
Console.WriteLine()
Console.WriteLine("That is an invalid Input.")
End If
Console.WriteLine()
Loop Until Row < 10 And Row >= 0
End Sub
Other code
'Skeleton Program for the AQA AS Paper 1 Summer 2016 examination
'this code should be used in conjunction with the Preliminary Material
'written by the AQA Programmer Team
'developed in the Visual Studio 2008 programming environment
'Version Number 1.0
Imports System.IO
Module Module1
Const TrainingGame As String = "Training.txt" ' Calls the training text file used by new players
Structure TShip ' Starts a new structure for use later that includes a stringed name and a size as an integer
Dim Name As String
Dim Size As Integer
End Structure
Sub MakePlayerMove(ByRef Board(,) As Char, ByRef Ships() As TShip) ' This part of the code advances on their column and row selection from earlier
Dim Row As Integer
Dim Column As Integer
GetRowColumn(Row, Column)
If Board(Row, Column) = "m" Or Board(Row, Column) = "h" Then ' m is miss h is a hit
Console.WriteLine("Sorry, you have already shot at the square (" & Column & "," & Row & "). Please try again.")
ElseIf Board(Row, Column) = "-" Then ' Message to user to say that they have shot in a sqaure they habe already shot in
Console.WriteLine("Sorry, (" & Column & "," & Row & ") is a miss.")
Board(Row, Column) = "m"
Else
Console.WriteLine("Hit at (" & Column & "," & Row & ").")
Board(Row, Column) = "h"
End If
End Sub
Sub SetUpBoard(ByRef Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
For Row = 0 To 9
For Column = 0 To 9
Board(Row, Column) = "-"
Next
Next
End Sub
Sub LoadGame(ByVal Filename As String, ByRef Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
Dim Line As String
Using FileReader As StreamReader = New StreamReader(Filename)
For Row = 0 To 9
Line = FileReader.ReadLine()
For Column = 0 To 9
Board(Row, Column) = Line(Column)
Next
Next
End Using
End Sub
Sub PlaceRandomShips(ByRef Board(,) As Char, ByVal Ships() As TShip)
Dim Valid As Boolean
Dim Row As Integer
Dim Column As Integer
Dim Orientation As Char
Dim HorV As Integer
For Each Ship In Ships
Valid = False
While Not Valid
Row = Int(Rnd() * 10)
Column = Int(Rnd() * 10)
HorV = Int(Rnd() * 2)
If HorV = 0 Then
Orientation = "v"
Else
Orientation = "h"
End If
Valid = ValidateBoatPosition(Board, Ship, Row, Column, Orientation)
End While
Console.WriteLine("Computer placing the " & Ship.Name)
PlaceShip(Board, Ship, Row, Column, Orientation)
Next
End Sub
Sub PlaceShip(ByRef Board(,) As Char, ByVal Ship As TShip, ByVal Row As Integer, ByVal Column As Integer, ByVal Orientation As Char)
Dim Scan As Integer
If Orientation = "v" Then
For Scan = 0 To Ship.Size - 1
Board(Row + Scan, Column) = Ship.Name(0)
Next
ElseIf Orientation = "h" Then
For Scan = 0 To Ship.Size - 1
Board(Row, Column + Scan) = Ship.Name(0)
Next
End If
End Sub
Function ValidateBoatPosition(ByVal Board(,) As Char, ByVal Ship As TShip, ByVal Row As Integer, ByVal Column As Integer, ByVal Orientation As Char)
Dim Scan As Integer
If Orientation = "v" And Row + Ship.Size > 10 Then
Return False
ElseIf Orientation = "h" And Column + Ship.Size > 10 Then
Return False
Else
If Orientation = "v" Then
For Scan = 0 To Ship.Size - 1
If Board(Row + Scan, Column) <> "-" Then
Return False
End If
Next
ElseIf (Orientation = "h") Then
For Scan = 0 To Ship.Size - 1
If Board(Row, Column + Scan) <> "-" Then
Return False
End If
Next
End If
End If
Return True
End Function
Function CheckWin(ByVal Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
For Row = 0 To 9
For Column = 0 To 9
If Board(Row, Column) = "A" Or Board(Row, Column) = "B" Or Board(Row, Column) = "S" Or Board(Row, Column) = "D" Or Board(Row, Column) = "P" Then
Return False
End If
Next
Next
Return True
End Function
Sub PrintBoard(ByVal Board(,) As Char)
Dim Row As Integer
Dim Column As Integer
Console.WriteLine()
Console.WriteLine("The board looks like this: ")
Console.WriteLine()
Console.Write(" ")
For Column = 0 To 9
Console.Write(" " & Column & " ")
Next
Console.WriteLine()
For Row = 0 To 9
Console.Write(Row & " ")
For Column = 0 To 9
If Board(Row, Column) = "-" Then
Console.Write(" ")
ElseIf Board(Row, Column) = "A" Or Board(Row, Column) = "B" Or Board(Row, Column) = "S" Or Board(Row, Column) = "D" Or Board(Row, Column) = "P" Then
Console.Write(" ")
Else
Console.Write(Board(Row, Column))
End If
If Column <> 9 Then
Console.Write(" | ")
End If
Next
Console.WriteLine()
Next
End Sub
Sub DisplayMenu()
Console.WriteLine("MAIN MENU") ' Main Menu Screen that is displayed to the user
Console.WriteLine()
Console.WriteLine("1. Start new game")
Console.WriteLine("2. Load training game")
Console.WriteLine(" 3. Change game limit")
Console.WriteLine("4. Load Saved Game")
Console.WriteLine("9. Quit")
Console.WriteLine()
End Sub
Function GetMainMenuChoice() ' Will check if the menu choice is picked can go through
Dim Choice As Integer ' Dim choice as an integer
Try
Console.Write("Please enter your choice: ") ' Ask user to enter their choice for the menu option
Choice = Console.ReadLine() ' User enters here
Console.WriteLine()
If Choice <> "1" And Choice <> "2" And Choice <> "9" And Choice <> "10" Then
Console.WriteLine("ERROR: Invalid input!") ' If their choice doesnt fit 1, 2 or 9 then it says this message
End If
Return Choice ' Return the choice to another part of code
Catch Ex As Exception
Console.WriteLine("Please enter a valid input (1, 2,9 or 10)")
End Try
End Function
Sub PlayGame(ByVal Board(,) As Char, ByVal Ships() As TShip)
Dim GameWon As Boolean = False
Dim score As Integer = 0
Dim gamelimit As Integer = 50
Do
PrintBoard(Board)
MakePlayerMove(Board, Ships)
score = score + 1
Console.WriteLine("You have taken {0} number of moves,", score)
GameWon = CheckWin(Board)
If GameWon Then
Console.WriteLine("All ships sunk!")
Console.WriteLine()
End If
Loop Until GameWon Or score = 50
If score = 50 Then
Console.WriteLine("You used all your moves up. Try again ")
End If
End Sub
Sub SaveGame(ByRef Board(,) As Char)
Dim SaveGameWrite As StreamWriter
SaveGameWrite = New StreamWriter("TEST.txt", True)
For x As Integer = 0 To 9
For y As Integer = 0 To 9
SaveGameWrite.Write(Board(x, y))
Next
Next
SaveGameWrite.Close()
End Sub
Sub LoadSavedGame(ByVal Filename As String, ByRef Board(,) As Char)
Dim Row, Column As Integer
Dim Line As String
Console.WriteLine("Load training game or open a saved game? T for training or S for saved")
If Console.ReadLine = "" Then
Console.WriteLine("Enter the filename: ")
Filename = Console.ReadLine
End If
Using FileReader As StreamReader = New StreamReader("C:\" & Filename)
For Row = 0 To 9
Line = FileReader.ReadLine()
For Column = 0 To 9
Board(Row, Column) = Line(Column)
Next
Next
End Using
End Sub
Sub SetUpShips(ByRef Ships() As TShip)
Ships(0).Name = "Aircraft Carrier"
Ships(0).Size = 5
Ships(1).Name = "Battleship"
Ships(1).Size = 4
Ships(2).Name = "Submarine"
Ships(2).Size = 3
Ships(3).Name = "Destroyer"
Ships(3).Size = 3
Ships(4).Name = "Patrol Boat"
Ships(4).Size = 2
End Sub
Sub Main()
Dim Board(9, 9) As Char
Dim Ships(4) As TShip
Dim MenuOption As Integer
Do
SetUpBoard(Board)
SetUpShips(Ships)
DisplayMenu()
MenuOption = GetMainMenuChoice()
If MenuOption = 1 Then
PlaceRandomShips(Board, Ships)
PlayGame(Board, Ships)
ElseIf MenuOption = 2 Then
LoadGame(TrainingGame, Board)
PlayGame(Board, Ships)
ElseIf MenuOption = 3 Then
PlaceRandomShips(Board, Ships)
PlayGame(Board, Ships)
End If
Loop Until MenuOption = 9
End Sub
End Module
Thanks in advance,
The Scottish Warrior
I need a little help. My code is work 99% correctly except for one little thing.
I'm making what's called "Cafeteria Survey" which tallies responses from a ComboBox, which the user inputs them self.
The issue here is that it tallies (places a *) the number 1 less than the number I chose in the ComboBox.
If I add + 1 on the end of SelectedIndex it places the * with the correct number, but it doesn't do it for #10
responses(ratingComboBox.SelectedIndex) += 1
Any help would be fantastic. Thanks in advance.
Here's my code:
Public Class CafeteriaSurveyForm
Dim choices As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim responses(0 To 11) As Integer
Dim responseCounter As Integer = 0
' displays histogram
Sub DisplayHistogram()
outputTextBox.Text = ("Rating" & vbTab & "Frequency")
For i As Integer = 0 To choices.GetUpperBound(0)
For ii As Integer = 1 To responses(i)
outputTextBox.Text &= ("*")
Next
outputTextBox.Text &= (vbNewLine & choices(i) & vbTab)
Next
End Sub ' DisplayHistogram
Private Sub CafeteriaSurveyForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ratingComboBox.DataSource = choices
End Sub
Private Sub submitButton_Click(sender As System.Object, e As System.EventArgs) Handles submitButton.Click
responseCounter += 1
responses(ratingComboBox.SelectedIndex) += 1
DisplayHistogram()
End Sub
End Class ' CafeteriaSurveyForm
Your display function is a little backward. Here is what you have now:
For i As Integer = 0 To choices.GetUpperBound(0)
For ii As Integer = 1 To responses(i)
outputTextBox.Text &= ("*")
Next
outputTextBox.Text &= (vbNewLine & choices(i) & vbTab)
Next
For every loop it is writing the asterisks to the previous line (because the new line is done after). If you increase the selected index it wrote them in the correct location but never got to write the asterisks for #10 because it exited the for loop before it got a chance.
This is what it should be:
For i As Integer = 0 To choices.GetUpperBound(0)
outputTextBox.Text &= (vbNewLine & choices(i) & vbTab)
For ii As Integer = 1 To responses(i)
outputTextBox.Text &= ("*")
Next
Next
Or even
For i As Integer = 0 To choices.GetUpperBound(0)
outputTextBox.Text &= vbNewLine & choices(i) & vbTab & New String("*", responses(i))
Next
Now the choices and responses arrays are synced using the same indexes and are accessed during the same loop iteration.
Maybe the error is that Responses(i) is defined to be integers in the range 1 to 11. If that range isn't inclusive that when you increment Responses(i) by 1 for the response 10 you will fall out of that range.
Try this out to see if it gives you the expected output.
Remove the responseCounter variable. It doesn't do anything significant (not any I see anyway).
Change the responses declaration to Dim responses(9) As Integer.
VB.NET uses zero (0) as the lower bound of an array (and almost every other type of collection) so the statement will create an array of integer with ten (10) elements.
Change the For ii As Integer = 1 to responses(i) loop block to outputTextBox.Text &= New String('*', responses(i))