My VB.NET program is giving me two errors:
It does not break when I enter a negative value or 0.
It does not show me the total values.
Can anyone help me with this problem?
Enter deposit amount: 300
Another (y or n)? y
Enter deposit amount: -1
Amount cannot be zero or negative.
My Code:
Module Module1
Sub Main()
Dim userResponse As Char
Dim depositAmount As Decimal
Dim totalDeposits As Decimal
Dim depositCount As Integer
Dim averageDeposit As Decimal
depositCount = 0
totalDeposits = 0
While Not (userResponse = "n")
Console.WriteLine("Enter Desposit Amount:")
If (depositAmount < 0 And depositAmount = 0) Then
Console.WriteLine("Amount cannot be zero or negative.")
Else
depositAmount = Console.ReadLine()
Console.WriteLine("Another (y or n)?")
userResponse = Console.ReadLine()
totalDeposits = totalDeposits + depositAmount
depositCount = depositCount + 1
averageDeposit = totalDeposits / depositCount
End If
End While
Console.WriteLine(" Total deposits: " + totalDeposits.ToString)
Console.WriteLine(" Number of deposits: " + depositCount.ToString)
Console.WriteLine("Average deposit: " + averageDeposit.ToString)
End Sub
End Module
You may be able to try: If (depositAmount < 0 or depositAmount = 0) From what I see the value cannot be negative and zero at the same time.
It does not break when I enter a negative value or 0.
It does not show me the total values.
You're coding without your options turned on and trying to implicitly convert string to Decimal. Also you're checking depositamount before the user enters it.
try something like this:
Module Module1
Sub Main()
Dim userResponse As Char
Dim depositAmount As Double
Dim totalDeposits As Double
Dim depositCount As Integer
Dim averageDeposit As Double
depositCount = 0
totalDeposits = 0
While Not (userResponse = "n")
Console.WriteLine("Enter Desposit Amount:")
'Attempt to convert readline to double. if it's successful GoodResponse
'is true and depositamount has the value entered, otherwise it's 0
Dim GoodResponse As Boolean = Double.TryParse(Console.Readline(), depositAmount)
If Not GoodResponse OrElse depositAmount <=0 Then
depositAmount = 0
Console.WriteLine("Amount must be a number and cannot be zero or negative.")
End If
Console.WriteLine("Another (y or n)?")
userResponse = Console.ReadLine()
totalDeposits = totalDeposits + depositAmount
depositCount = depositCount + 1
averageDeposit = totalDeposits / depositCount
End If
End While
Related
I'm trying to figure out why my program is accepting non-integer values which it then converts to an integer by rounding. The first value the user enters is validated, however, the rest isn't. My program is meant to count the number of odd and even integer numbers the user has entered. Any help would be greatly appreciated.
Private Sub btnShow_Click(sender As System.Object, e As System.EventArgs) Handles btnAddNum.Click
Dim intInputNum As Integer
Dim strInputNum As String = ""
Dim isEven As Integer = 0
Dim isOdd As Integer = 0
Dim userInput As String = InputBox(("Enter a number (0 to end)"))
Dim numArray() As String = strInputNum.Split(New Char() {","c})
Dim validInput As Boolean = Integer.TryParse(userInput, intInputNum)
If validInput = False Then
MsgBox("Invalid input, integer numbers only")
ElseIf validInput = True Then
Do While intInputNum > 0 And validInput = True
If intInputNum Mod 2 = 0 And validInput = True Then
lblEvenValues.Text = lblEvenValues.Text & CStr(intInputNum) & ","
intInputNum = Val(InputBox("Enter a number (0 to end)"))
isEven = isEven + 1
lblCountEven.Text = isEven
ElseIf intInputNum Mod 2 <> 0 And validInput = True Then
lblOddValues.Text = lblOddValues.Text & CStr(intInputNum) & ","
intInputNum = Val(InputBox("Enter a number (0 to end)"))
isOdd = isOdd + 1
lblCountOdd.Text = isOdd
ElseIf validInput = False Then
MsgBox("Invalid input, integer numbers only")
End If
Loop
End If
End Sub
This line:
Do While intInputNum > 0
is causing you issues. When the user inputs a non-integer value, after the first loop, this line: Val(InputBox("Enter a number (0 to end)")) evaluates to zero.
Which is obviously not greater than 0.
Reuse your boolean statement to evaluate userInput, not intInputNum like so:
userInput = Val(InputBox("Enter a number (0 to end)"))
validInput = Integer.TryParse(userInput, intInputNum)
Then you need to fix your message box location to simply show up outside of your loop rather than in it. So when validInput <> True it will break the loop and output your Msgbox.
You will also need to fix your Do While statement to correctly evaluate userInput instead of intInputNum
I need help with one simple task:
Input an integer number n and output the sum: 1 + 2^2 + 3^2 + ... + n^2. Use input validation for n to be positive.
My code does not work and till now is:
Sub Main()
Dim inputNumber As Integer
Console.WriteLine("Please enter a positive number.")
inputNumber = Console.ReadLine()
If inputNumber <= 0 Then
Console.WriteLine("Please use only positive numbers > 0 !")
End If
Dim sum As Integer
Dim i As Integer = 1
For i = 1 To i <= inputNumber
sum = sum + (i * i)
i = i + 1
Next
Console.WriteLine(sum)
Console.ReadLine()
End Sub
Try these changes:
Dim inputNumber as Long ' not Integer. Also change sum, i.
...
inputNumber = CLng(Console.ReadLine) ' make it a number, not a string
...
Dim sum as Long ' yum
dim i as Long ' don't assign it here
for i = 1 to inputNumber ' don't use "<=" in a for loop
...
' i = i+1 ' Don't increment i within the loop, since the loop does that for you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Input As Integer
Input = TextBox1.Text
Dim i As Integer
i = 0
Dim x As Integer
x = 0
Dim y As Integer
y = 0
For a = 1 To Input
y = Math.Pow(a, (Input - i))
x = Math.Pow(a, (Input - i)) + x
i = i + 1
Next
Label1.Text = x
End Sub
I have this case where I need that the user enters some data. All I need is to allow the user to enter numbers from 0 to 100, if the user is entering an amount bigger than 100, than display a message like: please enter number from 0 to 100 and then show them again where they need to enter that number.
For example, Console.Write("Español: ") in the terminal is:
Español: ' the user should enter the number here
if the user enters more than 100, then display this:
Please enter number from 0 to 100. Español: ' here enter the number again
I was thinking on doing this as in the code below, with an If ... Else, but, is there a better way?
Here is the actual code:
Sub Main()
Dim Español1 As Integer
Dim Matematicas1 As Integer
Dim Ciencias1 As Integer
Dim EstudiosSociales1 As Integer
Dim Ingles1 As Integer
Dim ArtesPlasticas1 As Integer
Dim ArtesIndustriales1 As Integer
Select Case Menu
Case 2
Console.Write("Ingrese las notas: ")
Console.ReadLine()
Console.Write("Español: ")
' I was thinking on doing this
If Console.ReadLine() >= 100 Then
Console.Write("La nota debe ser 100 o menos: ")
Español1 = Console.ReadLine()
Else
Español1 = Console.ReadLine()
End If
If Español1 = True Then
Console.Write("Matematicas: ")
Matematicas1 = Console.ReadLine()
End If
Console.Write("Ciencias: ")
Ciencias1 = Console.ReadLine()
Console.Write("Estudios Sociales: ")
EstudiosSociales1 = Console.ReadLine()
Console.Write("Ingles: ")
Ingles1 = Console.ReadLine()
Console.Write("Artes plasticas: ")
ArtesPlasticas1 = Console.ReadLine()
Console.Write("Artes Industriales: ")
ArtesIndustriales1 = Console.ReadLine()
Console.Clear()
End Select
End Sub
So, any suggestions?
I'm not really experienced with VB, but try this:
Dim n as Integer
n = Console.WriteLine()
Do While n >= 100
Console.WiteLine("Enter new Value:") 'Sorry, no pienso la lengua español :(
n = Console.ReadLine()
Loop
Edit 3.0
Add your subject names into the array subjects.
Sub Main()
Dim subjects As Array = {"Math", "English", "German"} 'Three example names
Dim subjectsInt As New Dictionary(Of String, Integer)
Dim i, input As Integer
Dim check, FirstTry As Boolean
For i = 0 To (subjects.Length - 1)
check = False
FirstTry = True
Do
If FirstTry = True Then
Console.WriteLine(subjects(i) & ": ")
FirstTry = False
Else
Console.WriteLine("Please enter a value between 1 and 100" & " (" & subjects(i) & "):")
End If
input = Console.ReadLine()
If input <= 100 And input > 0 Then
subjectsInt.Add(subjects(i), input)
check = True
End If
Loop While check = False
Next
For i = 0 To (subjects.Length - 1)
Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
Next
Console.ReadLine()
End Sub
Well I dont know VBA unfortunately . But I believe in every language is the same. You do a do {}while cycle and in the while you check if you conditions are met. And until they are met you continue reading from the console. Good look with your VBA :)
when i inpot Decimal numbers to textbox, the output will be one word
EX:
input:
textbox.text = 11311711511597105
output:
textbox.text = qussai
You should show us what you had tried.
The full code should be like this:
Module VBModule
Sub Main()
Dim output As String = DecimalToASCII("113117115115097105")
Console.WriteLine(output)
End Sub
Function DecimalToASCII(ByVal input As String) As String
Dim current As String = ""
Dim temp As Integer = 0
If input.Length Mod 3 <> 0 Then
Return "Wrong Input"
End If
For i As Integer = 0 To input.Length - 1 Step 3
temp = 0
For j As Integer = i To i + 2
temp *= 10
temp += CType(input(j).ToString(), Integer)
Next
current &= Chr(temp).ToString()
Next
Return current
End Function
End Module
I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If