Q. Accept two numbers using an InputBox in two different variables and print the sum of two in a message box. (Visual Basic) - vb.net

I have to answer this in Visual Basic.I actually don't have any idea how to solve this, our teacher barely teaches us practical stuff. I have to submit this assignment by today too.
I have tried to do solve it and searched the internet for it, but I could barely understand it.

Here is some code you can build upon:
Public Sub AddTwoNumbers()
Dim FirstNumber As String = Convert.toInt32(InputBox("Enter the first number.")) 'Get the first number
Dim SecondNumber As String = Convert.toInt32InputBox("Enter the second number.")) 'Get the second number
Dim Result As Integer = 0 'Used to store the result in
'Now perform the calculation.
Result = FirstNumber + SecondNumber
'Then show the result in a MessageBox
MessageBox.Show("The result is: " & Result.ToString())
End Sub

Here's an example using Integer.TryParse():
Dim value1, value2 As Integer
Dim response As String = InputBox("Enter first Integer:")
If Integer.TryParse(response, value1) Then
response = InputBox("Enter second Integer:")
If Integer.TryParse(response, value2) Then
Dim sum As Integer = value1 + value2
MessageBox.Show("The sum of " & value1 & " and " & value2 & " is " & sum)
Else
MessageBox.Show(response & " is not a valid Integer!")
End If
Else
MessageBox.Show(response & " is not a valid Integer!")
End If

Related

Building and coding a program to draw a rectangle of asterisks in visual basic

I am trying to build a for loop that greats a rectangle with asterisks where a user can enter the number of rows and columns they would wish displayed. I am able to get the rows working correctly but I unable to get the columns to work as they should. Could anyone correct me on where am going wrong:
Private Sub cmdProcess_Click(sender As Object, e As EventArgs) Handles cmdProcess.Click
Dim rows As Integer
Dim columns As Integer
rows = txtRow.Text
columns = txtColumn.Text
lbloutput.Text = ""
For i = 1 To rows
lbloutput.Text = lbloutput.Text & "*" & vbCrLf
Next
End Sub
Before anything else: your code will error if the user enters a negative number, or 0. Unless you have any other code to address this, you might want to try something like this:
rows = Abs(cInt(txtRow.Text))
columns = Abs(cInt(txtColumn.Text))
if rows*columns < 1 Then Exit Sub
(If your code is in VBA, rather than VB, then there is no advantage to using Integer over Long, as they both use the same amount of memory — an Integer just locks half of it out as unusable)
A naïve approach would be to use two loops, like so:
lbloutput.Text = ""
For i = 1 To rows 'How many lines of text?
For j = 1 to columns 'How many asterisks per line?
lbloutput.Text = lbloutput.Text & "*"
Next j
lbloutput.Text = lbloutput.Text & vbCrLf
Next i
However, a simpler method would be to use the String function:
lbloutput.Text = ""
For i = 1 To rows
lbloutput.Text = lbloutput.Text & String(columns, "*") & vbCrLf
Next i

Vb.net Data is not being incremented and added to list

I'm having an issue trying to create a program that takes user input for a text file's location containing medical records. The diseases and number of patients are being added to a list. I'm having an issue where my console is printing 0 for both the total of XX unique diseases and YYY patient encounters. I am not getting any errors, just not the correct output.
I believe my issue is in my processData() sub, however I am unsure why it's printing back 0. Also, how do I go about keeping track of duplicate diseases that are added to the list as I'm trying to add a counter next to each time the disease is seen.
Sample from Disease.txt
3710079 JUDITH CLOUTIER 2012-08-04 Spastic Colonitis
3680080 VIRGINIA ALMOND 2012-07-25 Chronic Phlegm
3660068 ELLEN ENGLEHARDT 2012-04-06 Whooping Cough
3810076 LILLIAN KEMMER 2014-07-04 Scurvy
3630055 TERESA BANASZAK 2012-06-15 Scurvy
Output:
There were a total of 0 unique diseases observed.
A total of 0 patient encounters were held
Main():
' Global variables
Dim inputFile As String
Dim patientCounter = 0
Dim diseaseList As New List(Of String)
Dim dateList As New List(Of Date)
Sub Main()
Dim reportFile As String
Dim yn As String
Console.ForegroundColor = ConsoleColor.Yellow
Console.BackgroundColor = ConsoleColor.Blue
Console.Title = "Medical Practice Data Analysis Application"
Console.Clear()
Console.WriteLine("Please enter the path and name of the file to process:")
inputFile = Console.ReadLine
If (File.Exists(inputFile)) Then
' Call to processData sub if input file exists
processData()
Console.WriteLine(vbCrLf & "Processing Completed...")
Console.WriteLine(vbCrLf & "Please enter the path and name of the report file to generate")
reportFile = Console.ReadLine
File.Create(reportFile).Dispose()
If (File.Exists(reportFile)) Then
Console.WriteLine(vbCrLf & "Report File Generation Completed...")
Else
' Call to sub to end program if directory does not exist
closeProgram()
End If
' Get user input to see report
Console.WriteLine(vbCrLf & "Would you like to see the report file [Y/n]")
yn = Console.ReadLine
' If user inputs "y" or "Y" then print report
' Otherwise close the program
If (yn = "y" OrElse "Y") Then
printFile()
Else
closeProgram()
End If
Else
' Call to sub to end program if file does not exist
closeProgram()
End If
Console.ReadLine()
End Sub
processData Sub():
Public Sub processData()
Dim lines As String() = File.ReadAllLines(inputFile)
Dim tab
Dim dates
Dim diseaseCounter = 0
For Each line As String In lines
tab = line.Split(vbTab)
patientCounter += 1
dates = Date.Parse(line(3))
dateList.Add(dates)
'diseaseList.Add(line(4))
Dim disease As New disease(line(4))
diseaseList.Add(disease.ToString)
'diseaseList(line(4)).
For Each value In diseaseList
'If value.Equals(line(4)) Then disease.counter += 1
Next
Next
Dim uniqueDiseases As String() = diseaseList.Distinct().ToArray
End Sub
Disease.class
Class disease
Dim counter As Integer = 0
Dim name As String = ""
Sub New(newDisease As String)
name = newDisease
counter = 0
End Sub
End Class
printFile()
Sub printFile()
Dim muchoMedical As String = "MuchoMedical Health Center"
Dim diseaseReport As String = "Disease Report For the Period " & "earliest_date" & " through " & "latest_date"
Console.WriteLine(vbCrLf & muchoMedical.PadLeft(Console.WindowWidth / 2))
Console.WriteLine(diseaseReport.PadLeft(Console.WindowWidth / 2))
Console.WriteLine(vbCrLf & "There were a total of " & diseaseList.Count & " unique diseases observed")
Console.WriteLine("A total of " & patientCounter & " patient encounters were held")
Console.WriteLine(vbCrLf & "Relative Histogram of each disease")
For Each disease As String In diseaseList
Console.WriteLine(vbCrLf & disease & vbTab & " ")
Next
End Sub
closeProgram()
Sub closeProgram()
Console.WriteLine(vbCrLf & "File does not exist")
Console.WriteLine("Press Enter to exit the program...")
Console.ReadLine()
End Sub
You don't need a disease class, really, if the most complicated thing you are doing is counting disease occurrences (your disease class had no public members so I don't know what you were doing there anyway). You can simply do everything with a little LINQ.
' processing section
Dim lines = File.ReadAllLines(inputFile)
Dim splitLines = lines.Select(Function(l) l.Split({vbTab}, StringSplitOptions.RemoveEmptyEntries))
Dim diseaseGrouping = splitLines.GroupBy(Function(s) s(3))
Dim patients = splitLines.Select(Function(s) s(1))
Dim dates = splitLines.Select(Function(s) DateTime.Parse(s(2)))
' report section
Dim padAmount = CInt(Console.WindowWidth / 2)
Dim muchoMedical As String = "MuchoMedical Health Center"
Dim diseaseReport As String = $"Disease Report For the Period {dates.Min():d} through {dates.Max():d}"
Console.WriteLine()
Console.WriteLine(muchoMedical.PadLeft(padAmount))
Console.WriteLine(diseaseReport.PadLeft(padAmount))
Console.WriteLine()
Console.WriteLine($"There were a total of {diseaseGrouping.Count()} unique diseases observed.")
Console.WriteLine($"A total of {patients.Count()} patient encounters were held")
For Each diseaseAndCount In diseaseGrouping
Console.WriteLine()
Console.WriteLine($"{diseaseAndCount.Key}{vbTab}{diseaseAndCount.Count()}")
Next
I think your disease name is in index 3. You were looking at 4 originally. Maybe you have a tab between first and last name? Change it if I was wrong. This may apply to any or all of the indices.
Output:
MuchoMedical Health Center
Disease Report For the Period 4/6/2012 through 7/4/2014
There were a total of 4 unique diseases observed.
A total of 5 patient encounters were held
Spastic Colonitis 1
Chronic Phlegm 1
Whooping Cough 1
Scurvy 2
I think the main issue with your code as listed above is that in the processData sub you have:
For Each line As String In lines
tab = line.Split(vbTab)
patientCounter += 1
dates = Date.Parse(line(3))
dateList.Add(dates)
'diseaseList.Add(line(4))
Dim disease As New disease(line(4))
diseaseList.Add(disease.ToString)
'diseaseList(line(4)).
For Each value In diseaseList
'If value.Equals(line(4)) Then disease.counter += 1
Next
Next
I think you more likely mean to use tab(3) and tab(4) instead of line(3) and line(4) etc. You split the line into the "tab" variable but then don't use it. While you could rewrite everything and handle it differently, if you want to go with what you've got, I think that's your core error.
I liked your idea of a class. You can wrap up all your data in one list. I enhanced your class so it could contain all the data in the file. Public Properties are automatic properties that have Get, Set, and the Private fields that hold the data written by the compiler. I have added an Overrides of the .ToString because you were not getting the results you expected. We have the parameterized constructor like you have except expanded to include all the properties.
The magic comes in the Linq query. The d stands for an item in the diseaseList which is an instance of the Disease class. Then I added an order by clause which will produce the results in alphabetical order by DiseaseName which is a string. Grouping by the unique DiseaseName into a Group with Count.
Notice in the second For Each loop we have all the properties of the class available.
I happened to be in a Windows Forms app so I used Debug.Print. Just replace with Console.WriteLine. I leave to you the fancy formatting if you desire.
Public Class Disease
Public Property Name As String
Public Property DiagnosisDate As Date
Public Property DiseaseName As String
Public Property ID As Integer
Public Sub New(PatientID As Integer, PatientName As String, dDate As Date, sDisease As String)
ID = PatientID
Name = PatientName
DiagnosisDate = dDate
DiseaseName = sDisease
End Sub
'If you don't override ToString you will get the fully qualified name of the class
'You can return any combination of the Properties as long as the end
'result is a string
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Public Sub processData()
Dim lines As String() = File.ReadAllLines(inputFile)
Dim diseaseList As New List(Of Disease)
For Each line As String In lines
'I was having trouble with the tabs so I changed it to a comma in the file
'3710079,JUDITH CLOUTIER,2012-08-04,Spastic Colonitis
'the small c following the "," tells the compiler that this is a Char
Dim tab = line.Split(","c)
Dim inputDate = Date.ParseExact(tab(2), "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim Studentdisease As New Disease(CInt(tab(0)), tab(1), inputDate, tab(3))
diseaseList.Add(Studentdisease)
Next
Dim diseaseGrouping = From d In diseaseList
Order By d.DiseaseName
Group By d.DiseaseName
Into Group, Count
For Each diseaseAndCount In diseaseGrouping
Debug.Print($"{diseaseAndCount.DiseaseName} {diseaseAndCount.Count()} ")
For Each d In diseaseAndCount.Group
Debug.Print($" {d.Name}, {d.DiagnosisDate.ToShortDateString}")
Next
Next
End Sub

If a listbox contains an item LIKE

Is there anywhere to check whether a listbox contains an item which is similar to a string?
I have tried to use a Like statement but this doesn't work.
I have tried:
For i As Integer = 0 To TopicListBox.Items.Count - 1
If (TopicListBox.Items(i).ToString.Contains(Record.Item("Keyphrase2"))) Then
Dim Item As String = TopicListBox.Items(i).ToString
If Item Like "Questions related to:" & Record.Item("Keyphrase2") & ": |*| Qs" Then
Dim ItemSplit() As String = Item.Split(New Char() {"|"c})
Dim AmountOfQuestionsAfter As Integer = AmountOfQuestions + CInt(ItemSplit(1))
Item = ItemSplit(0) & AmountOfQuestionsAfter & ItemSplit(1)
Else
TopicListBox.Items.Add("Questions related to:" & Record.Item("Keyphrase2") & ": |" & AmountOfQuestions & "| Qs")
Exit For
End If
End If
Next
I don't really understand what you are trying to accomplish, but here is a LINQ function to return all the items that contain a certain string.
Dim lb As New ListBox
lb.Items.Add("asdf")
lb.Items.Add("asdfasdf")
lb.Items.Add("aifisasdf")
lb.Items.Add("adf")
'' find all items in the ListBox that contain the string "asdf"
Dim found = lb.Items.Cast(Of String).Where(Function(f) f.Contains("asdf"))
For Each s In found
'' do something with those items
Next
Can't you just do
If Item.Contains("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
or
If Item.StartsWith("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
?
Dim Found = (From Result In lb.Items Where Result.ToString = "Value" Select Result)
If (Found.Count > 0) Then
' your code
End If

Check if a string variable has an integer value

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)
A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If
Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then
You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.
IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub
Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian
Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If
Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer
In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN

Only numbers, disallow letters -user input

I am writing a console application which requires user input of certain values. I want to disallow any letter input. The console automatically writes "Conversion from string "b" to type 'Integer' is not valid." but I want the console to display my personal message "Not a valid number, please try again." how can I do that?
I've tried many different keywords and phrases but none work. Maybe I'm doing it wrong (not unlikely) or maybe it's just meant for something else. Either way I need help.
To recap: User input in a console that only allows numbers not letters, and will display my message.
I didn't want to post my code since people always pick on it, but here it is. Please note that there MUST be an exception. It is homework and I NEED an exception and this is one way a user can screw up. Please don't tell me not to use an exception.
Module Module1
Sub Main()
Try
System.Console.WriteLine("Input up to 10 valid numbers to have them mathematically averaged.")
For Index = 0 To 9
Dim Input As IList
Input = Console.ReadLine()
Next Index
If ' here is where I want to add that numbers only Then
Throw New exception("Not a valid number, please try again.")
Else
System.Console.WriteLine("Now averaging numbers...")
Dim average As Double = (n + n + n + n + n + n + n + n + n + n) / 10
Console.WriteLine("The average of " & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & "," & n & " and " & n & " is " & average & ".", "Calculation")
End If
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module
Dim inputString = Console.ReadLine
If Integer.TryParse(inputString, num) Then
DoSomething(num)
Else
Console.WriteLine("Not a valid number, please try again.")
End If
Here's one way to do it, honoring your requirements:
Module Module1
Sub Main()
System.Console.WriteLine("Input valid numbers seperated by spaces to have them mathematically averaged.")
Dim inputArray As String() = System.Text.RegularExpressions.Regex.Replace(Console.ReadLine().Trim(), "\s{2,}", " ").Split(New Char() {" "})
Dim values As New ArrayList
Dim sum As Integer
For i As Integer = 0 To inputArray.Length - 1
Try
sum = sum + Integer.Parse(inputArray(i), Globalization.NumberStyles.Integer)
values.Add(inputArray(i))
Catch ex As Exception
Console.WriteLine(String.Format("The value ""{0}"" is not a valid number and will be ignored. ExceptionMessage: {1}", inputArray(i), ex.Message))
End Try
Next
Dim average As Decimal = sum / values.Count
Console.WriteLine(vbCrLf)
Console.WriteLine(String.Format("The average of ""{0}"" is {1}", Join(values.ToArray, ", "), average))
Console.WriteLine(vbCrLf)
Main()
End Sub
End Module
Well for starters, the Try - Catch should be inside the input gathering For loop. As your program is written now, as soon as one wrong value is entered execution jumps to the catch and your program ends! If you try casting your input to an decimal you won't need to throw an exception manually, it will be thrown automatically if your input is not an decimal! Try casting the current console input as a decimal and then add that number to your list.
Dim inputNumber as Decimal = CDec(Console.ReadLine())
Input.Add(inputNumber)
Also n will be the same number every time so how you are doing it won't work (look up the basics of how a list works, how to add elements to a list and how to display list elements)