I'm having difficulty calculating time differences in Visual Basic [closed] - vb.net

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Layout of Calculator
I am trying to build a program that calculates times differences in minutes. I do this by subtracting the start time from the finish time. I have four text boxes, two of which are for the time unit of hours (h), and the other two are for minutes (m).
a is the starting time in hours and c is the finish time in hours. They are being multiplied by 60 to convert the hours to minutes. I want to calculate the time difference between 5:40pm and 7:15pm but some how end up with 567 when the answer should be 95.
This is not a homework task, I'm a lazy learner driver in Australia who wants to create a simple program that calculates the time of a journey in minutes.
Can somebody please tell me what I'm doing wrong?
Here is my code:
Public Class Calc
Dim Product
Dim a, b, c, d As Integer
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
a = Val(TextBox1.Text) * 60
b = Val(TextBox2.Text)
c = Val(TextBox3.Text) * 60
d = Val(TextBox4.Text)
Product = (c - a + d - b)
Time.Text = ("Driving Time: " & Product)
End Sub
End Class

I wasn't going to post this but I couldn't let the use of TimeSerial by Dy.Lee go unanswered. This code uses reasonable variable names, uses the correct type for time periods, i.e. TimeSpan, and also compiles with Option Strict On, which it should pretty much always be. I'd get rid of that Val usage too but I couldn't be bothered here.
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
Dim startHours = CInt(Val(TextBox1.Text))
Dim startMinutes = CInt(Val(TextBox2.Text))
Dim endHours = CInt(Val(TextBox3.Text))
Dim endMinutes = CInt(Val(TextBox4.Text))
Dim startTime As New TimeSpan(startHours, startMinutes, 0)
Dim endTime As New TimeSpan(endHours, endMinutes, 0)
Dim timeDifference = endTime - startTime
Time.Text = ("Driving Time: " & timeDifference.TotalMinutes)
End Sub
EDIT: It also declares variables in the appropriate place, i.e. in the method they're being used in. If you're using those same variables elsewhere then you'd have to stick with fields but I'm guessing that you're not doing so.
EDIT: Here's a version without the dodgy Val calls and some proper validation. You could combine all the If statements into one but separating them allows you to display different messages based on the type of issue.
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
Dim startHours As Integer
Dim startMinutes As Integer
Dim endHours As Integer
Dim endMinutes As Integer
If Integer.TryParse(TextBox1.Text, startHours) AndAlso
Integer.TryParse(TextBox2.Text, startMinutes) AndAlso
Integer.TryParse(TextBox3.Text, endHours) AndAlso
Integer.TryParse(TextBox4.Text, endMinutes) Then
If startHours < 24 AndAlso
startMinutes < 60 AndAlso
endHours < 24 AndAlso
endMinutes < 60 Then
Dim startTime As New TimeSpan(startHours, startMinutes, 0)
Dim endTime As New TimeSpan(endHours, endMinutes, 0)
If startTime < endTime Then
Dim timeDifference = endTime - startTime
Time.Text = ("Driving Time: " & timeDifference.TotalMinutes)
Else
'Notify user of invalid input.
End If
Else
'Notify user of invalid input.
End If
Else
'Notify user of invalid input.
End If
End Sub

#PaulHebert pointed out to me that I needed to swap around textbox 3 & 4 because I was treating the wrong fields as hours. The math had made sense in my head so I probably overlooked a rather simple yet inconvenient mistake. I want to thank everyone who tried to help :) Merry Christmas!

Your math is wrong you are subtracting the hours and then adding them to the difference of minutes. You need to get the total number of minutes since midnight from each time and then subtract those. Then get the absolute value so you don't have negative minutes
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles Enter.Click
a = Val(TextBox1.Text) * 60
b = Val(TextBox2.Text)
c = Val(TextBox3.Text) * 60
d = Val(TextBox4.Text)
Product = Math.Abs((c +d) - (a + b))
Time.Text = ("Driving Time: " & Product)
End Sub

Try using this code
Private Sub Enter_Click(sender As Object, e As EventArgs) Handles
a = CInt(Trim(TextBox1.Text)) * 60
b = CInt(Trim(TextBox2.Text))
c = CInt (Trim(TextBox3.Text)) * 60
d = CInt(Trim(TextBox4.Text))
Product = (c + d) - (a + b)
Time.Text = ( "Driving Time: " & Product)
End Sub
Also make sure that the text boxes are properly arranged. Text box 1 should come first followed by the others.

Related

VB.NET Divisions problems

First of all, I would like you to know that I am really rookie on this platform and in vb.net language. I have a question, I wanted to ask you, since I couldn't make any progress in about 3 hours. I think it's very simple for someone who knows.
If the number entered from the textbox is odd, multiply by 3 and add 1, if it is double, this process will be divided by 2, and this process should continue until the number is "1". I try to write the code of the program that finds how many steps this process takes (number of processes), the maximum value of the number during the process and the number that the number always reaches 1 in pairs with VB.NET.
Is there anyone who can help? I want you to know that I was really struggling, trying to learn, but not enough
As I said, I scribbled something, but I am not even on the right track.
enter image description here
enter code here
Dim number1 As Double
Dim tislem As Double
Dim result As Double
Dim çislem As Double
Dim i As Double
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
çislem = number1 / 2
tislem = number1 * 3 + 1
If number1 Mod (2) = 1 Then
result = tislem
MessageBox.Show("sayı tektir" + result.ToString())
For i = 1 To result = 0
result = number1 / 2
Next i
MessageBox.Show("sayı tektir" + result.ToString())
Else MessageBox.Show("sayı çifttir")
End If
End Sub
I'm not sure if I understood exactly what you're trying to do (neither of us have english as a first language it seems). I'm still trying, but make sure that you understand what I'm doing or I may lead you off target.
It seems to me that the worst problem here is using a For loop instead of a While loop. You could also do without some of these variables. Here's some code to give you a hand:
' I suggest that you add these two lines at the very top of your code
' It'll force you to type your variables, which is a great way to avoid all kind of mistakes
Option Explicit On
Option Strict On
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Here I'm protecting you against errors caused if the user enters a non-numeric
' Your teached probably didn't ask for this but it's good to know nonetheless
If Not String.IsNullOrWhiteSpace(TextBox1.Text) AndAlso IsNumeric(TextBox1.Text) Then
' Converting text to double (it was done implicitely in your code, but it's better to understand what's happening to better control it)
Dim myNumber As Double = CDbl(TextBox1.Text) ' CDbl as in 'Convert DouBLe'
Dim maxNumber as Double = myNumber
' If the number is odd, we multiply by 3 and add 1
If myNumber Mod 2 = 1 Then
myNumber = (myNumber * 3) + 1
If myNumber > maxNumber Then maxNumber = myNumber
End If
' Let's count how many divisions before there's only 1 left
Dim i As Integer = 0
While (myNumber > 1)
myNumber = myNumber / 2
i += 1
End While
MessageBox.Show("It took " & i.ToString & " divisions until my number was reduced to 1. The max number was " & maxNumber.ToString & ".")
Else
' This will appear if you try to use non-numeric, like letters
MessageBox.Show("Use only numbers.")
End If
End Sub
Have fun!
Try something like this,
Dim number1 As Double
Dim maxNumber As Double = 0
Dim steps as Double = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
number1 = TextBox1.Text
MessageBox.Show($"Sayı {If( (number1 Mod 2) = 1, "tektir", "çifttir") }")
While number1 > 1
number1 = If((number1 Mod 2) = 1, number1 * 3 + 1, number1 * 2)
maxNumber = Math.Max(number1, maxNumber)
steps += 1
End While
MessageBox.Show($"Steps: {steps}{Environment.NewLine}Max number reached: {maxNumber}")
End Sub
You should write a proper loop in order to repeat this process until you reach 1. Moreover, it is better for you that if you get used to use & symbol instead of + symbol to concat strings.

Same number is generated in RNG in VB.NET

I am attempting to make a random number generator in VB 16 in Visual Studio, but every time I run this I keep getting 71, I've tried making it public, sharing it and several other things, but it won't work. I am trying to make a program that has the user guess a randomly generated number, and continue guessing until they get it, but for some reason the exact same number is chosen each time. It won't work properly specifically in window app forms. How do I get a random number each time?
Public Shared Randomize()
Dim value As Integer = CInt(Int((100 * Rnd()) + 1))
Public Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Dim entervalue As String = EnterTxt.Text
Dim chances As Integer
Select Case entervalue
Case > value
ResTxt.Text = "Too big"
chances += 1
Case < value
ResTxt.Text = "Too small"
chances += 1
Case = value
ResTxt.Text = "Well done, you got it in " & chances & " tries"
End Select
End Sub
You were close! Here's a working example modifying your original logic:
Private random As Random = New Random()
Private value As Integer
Private chances As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
value = random.Next(1, 100)
chances = 0
End Sub
Private Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Select Case EnterTxt.Text
Case > value
chances += 1
ResTxt.Text = "Too big"
Case < value
chances += 1
ResTxt.Text = "Too small"
Case = value
chances += 1
ResTxt.Text = "Well done, you got it in " & chances & " tries"
'and reset for next attempt
value = random.Next(1, 100)
chances = 0
End Select
End Sub
Since your code is not correct it is hard to pinpoint the problem. It is also not clear what the code is supposed to do.
Try this
Private Shared PRNG As New Random ' add this
value = PRNG.Next(1, 101)'this will set value to a random number between 1 and 100 inclusive
Here's some skeleton code for you:
Dim rnd As New Random()
For i as Integer = 0 to 10
Console.WriteLine("{0,15:N0}", rnd.Next())
Next
Notice the rnd.Next() thing. Hope it helps.

How to I make the values in the list box round to two decimal places with this visual basic code

I have written this code in visual basic to solve a basic interest calculation. The year end balances are shown in the list box and the final total is show in the label. My problem is that I can not figure out how to round the values in the list box to two decimals. I have tried various things but with no luck so far so I appreciate any help.
Public Class frmNestEgg
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
' Declare and Initialize the variables
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For Years = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & Years & " Balance " & YrEndAmt)
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
Private Sub frmNestEgg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
you could use
Math.Round()
... & Math.Round(YrEndAmt, 2).ToString()
but your code had a flaw: same variable Years for looping and end condition
so change:
For Years = 1 To Years
to:
Dim Years As Integer, year As Integer
For year = 1 To Years
your entire code would then be:
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnPrincipal.Click
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer, year As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For year = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & year & " Balance " & Math.Round(YrEndAmt, 2).ToString())
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub

windows application in vb.net for calculating student marks

I need to make a vb.net windows application for calculating the student marks.I have three valuations.For example if valution1 is 45 marks and if valuation2 has 30 then there is 15 marks difference so valuation3 has to be done.Then average will be calculated by adding valuation 3 with maximum score of valuation1 and valuation2.valuation3 is done only when there is a difference of 15 or more marks in valuation1 and valuation2.Please help me to make this application as i am new to coding.
Get three textboxes, set the third textbox's enabled property to false. The following code will help you (under textbox's textchanged event).
Private Sub Hello () Handles Textbox1.Textchanged, Textbox2.Textchanged
If Val(Textbox1.Text) - Val(Textbox2.Text) >= 15 then
Textbox3.Enabled = True
Else
Textbox3.Enabled = False
End If
End Sub
For average, you need to add all the values and then divide by number of terms. Suppose you display the average in a label:
Dim a as integer
If Textbox3.Enabled = True then
a = Val(Textbox1.Text) + Val(Textbox2.Text) + Val(Textbox3.Text)
Label1.Text = a/3
Else
a = Val(Textbox1.Text) + Val(Textbox2.Text)
Label1.Text = a/2
End If
I hope you understand! This was a type of homework, but I did it just because I was bored. Please don't ask such questions in the future. Read the 'How to Ask' guide next time.

Formatting Time (HH:MM:SS)

I'm taking values from Numeric Ups and Downs for Hours, Minutes and Seconds.
The problem is that, for example, if the time for example is 9.15 am it will show as 9:15:0
What I want to do is format them so if any of the values(Hours, Minutes or seconds) is less than 10, it will add a 0 before the number so as the number shows as 09:15:00.
What I tried is this but it does not work:
Sub BtnSetClick(sender As Object, e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString + nmMin.Value.ToString + nmSec.Value.ToString
lblST.Text.Format(nmTime.ToString, "HH:MM:SS")
lblST.Text = (nmTime)
lblST.Visible = True
End Sub
You seem to be doing it a bit backward by converting everything to string multiple times, try something like this:
Dim ts As new TimeSpan(CInt(nmHour.Value), CInt(nmMin.Value), CInt(nmSec.Value))
lblST.Text = ts.ToString("HH:MM:SS")
The documentation for TimeSpan.ToString is useful.
Edit: Updated the code to reflect Tim's comment about datatype.
Try this:
Sub BtnSetClick(ByVal sender As Object, ByVal e As EventArgs)
lbl8.Visible = True
Dim nmTime As String = nmHour.Value.ToString().PadLeft(2, '0') + nmMin.Value.ToString().PadLeft(2, '0') + nmSec.Value.ToString().PadLeft(2, '0')
lblST.Text = nmTime
lblST.Visible = True
End Sub
try using the TimeSpan object, it should do all the hard work for you!
Dim nmTime As New TimeSpan(nmHour.Value, nmMin.Value, nmSec.Value)
lblST.Text = nmTime.ToString
lblST.Visible = True