Detect the sign in number input - vb.net

how can i detect if the input number in textbox contains "-"
so i can change the output into positive number and
if not contain "-" the output number is become negative
i'm using Vb.net 2010 tnx in advance for who wants to help

Dim output As String
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If getbyte(TextBox1.Text, 0) = Chr(45) Then ' check whether the first character is - or not
output = New String((From c As Char In TextBox1.Text Select c Where Char.IsDigit(c)).ToArray())
else
output="-" & textbox1.text
End If
msgbox (CInt(output))' will give the number
End Sub
Getbyte function to take each character from a string based on the position
Private Function getbyte(ByVal s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
if you want to convert the -eve number to positive for calculation you can use

You have couple of options, two of them are:
1) Use StartsWith functions:
If Textbox1.Text.Trim().StartsWith("-"))Then
' It is a negative number
End If
2) If you just need to toggle the number sign, then:
Dim number as Integer = Integer.Parse(Textbox1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Using option2, i get:
Dim txta1 As New TextBox
txta1.Text = "-2"
Dim number As Double = Double.Parse(txta1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Dim s As String = number & " | "
Output: 2 |

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.

Adding 1 everytime i use button vb.net

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.

VB - Caesar Cipher emulation

I'm trying to emulate Caesar Cipher encryption. The problem is whenever I input "wxyz"
(shifted by 3) the output is "z{|}". But the expected output should be "zabc".
Anyone knows what to add?
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim plaintext As String = TextBox1.Text
Dim charArray() As Char = plaintext.ToCharArray
Dim shift = TextBox2.Text
Dim character As String
Dim temp As String
TextBox3.Text = ""
If shift <> "" And IsNumeric(shift) Then
If plaintext = "" Then
MsgBox("Please input some plain text")
Exit Sub
End If
If shift > 26 Then
MsgBox("Maximum shifts reached. Limit is 26!!")
Exit Sub
End If
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
Exit Sub
Else
MsgBox("Input numbers only!!")
End If
End Sub
When you shift an Ascii code you should verify that it does not get greater than 122, which is the Ascii code for the character "z". If you go beyond that point, you will get punctuation marks, symbols and that stuff. Google "ASCII table" and you can easily see it for yourself.
So, to solve your problem, if the Ascii code you get after shifting is greater than 122 you should go back and begin by 97 again, which is the ascii for "a".
So, instead of this:
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
You should do something like
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
' You substract 26, the whole length of the alphabet
If character > 122 Then
character = character - 26
End If
TextBox3.Text += character
Next
No quite sure that this would be stable if shift is greater than 26, but anyhow you already check its value so it should work.

How to find the Sum or Total of a Listbox

I have a listbox that has two columns of date entered into it using the code:
'Press to place value into Array
Private Sub TxtMark_Enter(ByVal sender As System.Object, _
ByVal e As KeyEventArgs) Handles TxtMark.KeyDown
Dim Mark As Double
Dim DataString As String
If e.KeyCode = Keys.Enter Then
If Double.TryParse(TxtMark.Text, Mark) = False Then
MessageBox.Show(" You must enter a numeric value like 1 or 2")
TxtMark.Clear()
TxtMark.Focus()
Exit Sub
End If
If Mark < 0 Then
MessageBox.Show("Valid range is between 0 and 100, 7 would work " _
& Mark.ToString & " Does not")
TxtMark.Clear()
TxtMark.Focus()
Exit Sub
End If
If NumberOfScores < MaxEntries Then
ScoreArray(NumberOfScores) = Mark
DataString = (NumberOfScores + 1).ToString + ". " + _
NameArray(NumberOfScores).PadRight(15) + _
Mark.ToString.PadLeft(5)
Lstdisplay.Items.Add(DataString)
NumberOfScores += 1
End If
TxtMark.Clear()
TxtName.Clear()
TxtName.Focus()
Exit Sub
End If
What I want to do is have a label that does the some of the Mark automatically as the data is entered. Any ideas would be great
The solution is to iterate through all entries and add up the values:
Dim total As Double
For Each s As String In ListBox1.Items
total+= s.substring(...)
Next
Debug.WriteLine("The total is:" + total.ToString)
The tricky part is extracting the numeric value from the string.
But it would be much easier if you placed the data into a ListView control. With the values all in one column. Then you don't need to do the substring to extract the numeric values out
One idea would be to add a custom extension that returns the numeric part of the string and then use Matt Wilko's iteration as above.
To create a custom extension add a class to your project as follows:
Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Namespace Extensions
Public Module ExtensionMethods
<Extension()> _
Public Function GetNumeric(ByVal source As String) As String
'Takes the passed in string and returns the numeric part
Dim ReturnString As String = ""
For A = 1 To source.Length
If IsNumeric(source.Substring(A, 1)) Then
ReturnString += source.Substring(A, 1)
End If
Next
Return ReturnString
End Function
End Module
End Namespace
If you then import MyProject.Extensions on you project you can use string.GetNumeric to return the numeric part of your code.
Hope this helps you (and others).

VB program to calculate grades

So I am working on a program that will ask for the number of assignments, say 20, then run through a loop that many times asking for the total points earned on each assignment as well as the total points possible to get the final grade. For example if the user put in 2 assignments with assignment 1 earning 48 points out of 50 and assignment 2 earning 35 points out of 40 the program would display the grade as 92.
So far here is what I have:
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim amountAssignments As Integer
Dim pointsEarned As Integer = 0
Dim pointsEarnedTotal As Integer = 0
Dim pointsPossible As Integer = 0
Dim pointsPossibleTotal As Integer = 0
Dim Assignment As Integer = 1
Integer.TryParse(txtAmount.Text, amountAssignments)
Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
lblAmount.Text = "Enter Points Given on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsEarned)
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
lblAmount.Text = "Enter Points Possible on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsPossible)
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop
lblAmount.Text = "Enter the amount of Assignments: "
lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
End Sub
End Class
syntax is correct but when the program is run and the number of assignments put in and calculate entered the program displays the grade as NaN with no other input requested.
Could use another set of eye(s) to look over this and tell me where i screwed up logically.
Thank you in advance!
This program seems to not have some sort of user intervention when the loop starts. What I would do is surely have the user enter the amount of assignments on the textbox and then from there would ask the user to enter marks from an input box separated by a slash e.g I enter 45/50 so after input the program finds the index of "/",all characters before the '/' are the pointsEarned and can be added to the pointsEarnedTotal while all the characters after the '/' are placed in the pointsPossible and added to the pointsPossibleTotal
Try this and tell me how it goes...give me points if it works
` Private Sub butGetMarks_Click(sender As System.Object, e As System.EventArgs) Handles butGetMarks.Click
Dim assignments As Integer = 0
Dim totalAssignments As Integer
Integer.TryParse(txtAssignments.Text, totalAssignments)
Dim pointsEarned As Double = 0
Dim pointsEarnedTotal As Double = 0
Dim possibleEarned As Double = 0
Dim possibleEarnedTotal As Double = 0
Dim temp As String
For i As Integer = 1 To totalAssignments
temp = InputBox("Enter marks per assignment separated by /")
Dim i1 As Integer
i1 = temp.IndexOf("/") 'read index of /
pointsEarned = temp.Substring(0, i1) 'read from start until / character
possibleEarned = temp.Substring(i1 + 1) 'read from after / character onwards
'add to totals
possibleEarnedTotal += possibleEarned
pointsEarnedTotal += pointsEarned
Next i
MessageBox.Show(pointsEarnedTotal & "/" & possibleEarnedTotal)
End Sub`