Calculating value of user-inputted equation - vb.net

I'm working on building a simple limit calculator in Visual Studio 2013. Right now I have my program set up in a way so that the user first enters the equation for the limit, and then the limit value. (ex. equation of x+3, limit value of 3 - the answer should then be 6)
I'm designing it so that it takes the limit from both the left and right side of the user inputted number, and if the two answers then differ by quite a bit, the program will say the limit doesn't exist. (However this code isn't in place yet - I plan to work on it after I can solve this problem)
Anyway, right now I'm stuck on one part of my code. The user can input their own custom function, as I mentioned above. I then have the program automatically replace all "x" values with the limit value that the user input as well. However, when I have the answer display, it will give me an answer of 5.0001 + 3 instead of just 8.0001. Below is my code, do you know of any way I can fix this so that it will perform the calculations needed, and just spit out a single number rather than the equation with x substituted out?
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim Limit As Double = txtLimit.Text
Dim Equation As String = txtEquation.Text
Dim LeftTest As Double
Dim RightTest As Double
LeftTest = (Limit - 0.0001)
RightTest = (Limit + 0.0001)
Dim NewEquation = Replace(Equation, "x", RightTest)
Dim FinalAnswer
FinalAnswer = NewEquation
MsgBox("The limit for this equation is " & NewEquation)
End Sub
End Class
Any help would be appreciated with this.

You can download and use third party Parser.dll from the following link
http://simplemathparser.codeplex.com/
and code as shown below
Dim Limit As Double = txtLimit.Text
Dim Equation As String = txtEquation.Text
Dim LeftTest As Double
Dim RightTest As Double
LeftTest = (Limit - 0.0001)
RightTest = (Limit + 0.0001)
Dim parser As New MathParser.Parser("x")
Dim parsingResult = parser.Parse(Equation)
Dim result = parsingResult.Evaluate(RightTest)
MsgBox("The limit for this equation is " & result )

Related

Visual Basic percentage data saving failure

I have a problem with saving % data to database. I have a template, and if the % more, than 100%, the program Can't save the data properly. Could you explain me, why is that and what I have to do, to eliminate this problem?
Here is my code:
Sub xhusarany()
Dim xhusarany As String
Dim v As Integer
Dim cella As String
xhusarany = Sheets("gyártott termék").Range("n44").Value
cella = "ak" & adatsorszam
Sheets("adatbázis").Range(cella).Value = xhusarany
Call xhusaranyspec
End Sub
And here is a screenshot from my database with wrong saved data:
Thank you in advance!

Using check digit algorithm to determine whether a value inputed is valid?

I am writing code for a form that is supposed to determine whether a value inputted by the user is valid as a check digit. They input a 13 digit number and it should determine whether or not the last value is valid as a check digit. I have written in the code for the check digit algorithm but I'm having trouble with comparing the value that the algorithm found with what the user input. I have tried using the substring method to compare the 13th number given by the user with the check digit that the algorithm determined but I am having issues with the syntax of everything.
This is the code I have been working on:
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim intDigit As Integer
Dim intTotalOdd As Integer
Dim intTotalEven As Integer
Dim intGrandTotal As Integer
Dim intRemainder As Integer
Dim intCheckDigit As Integer
If txtNumber.Text.Length = 13 Then
For intOdd As Integer = 1 To 11 Step 2
intTotalOdd += (intDigit * 3)
Next intOdd
For intEven As Integer = 0 To 10 Step 2
intTotalEven += intDigit
Next intEven
intGrandTotal = intTotalOdd + intTotalEven
intRemainder = intGrandTotal Mod 10
If intRemainder <> 0 Then
intCheckDigit = 10 - intRemainder
End If
If txtNumber.Text.Substring(12, 13) = intCheckDigit Then
lblStatus = "Valid"
Else
lblStatus = "Not Valid"
End If
End If
End Sub
I think the way I'm doing it should work but I don't have very much to reference on how I would go about making the syntax work. Will the way that I'm trying to do it work or do I need to go about it in a different way?

Losing decimal while dividing in visual basic

I'm having to create a random math generator in visual basic, when a user selects divide it should show the number to the second decimal. Anything I have tried so far keeps rounding off.
option strict on is required
this is the code I have so far
Private Sub DivisionProblem()
' Divide two numbers and display the answer
Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()
Dim strToWork As String
If (numLargestNum > numSmallestNum) Then
strToWork = (Convert.ToString(numLargestNum) & " / " & Convert.ToString(numSmallestNum))
lblToWork.Text = strToWork
_decAnswer = CInt((Decimal.Round(CDec(numLargestNum / numSmallestNum), 2)))
Else
strToWork = (numSmallestNum & " / " & numLargestNum)
lblToWork.Text = strToWork
_decAnswer = CInt((Decimal.Round(CDec(numSmallestNum / numLargestNum), 2)))
End If
End Sub
if anyone has any suggestions I would greatly appreciate it. thank you!
CInt forces the value to be of Integer not Double.
Dim numSmallestNum As Integer = CreateANumber()
Dim numLargestNum As Integer = CreateANumber()
Declare these two As Decimal and there's no need to convert anything.
You'll want to Dim _decAnswer as Decimal and use CDec instead of CInt.
For additional context on the Decimal type, check out this article
You might also want to consider using Double and CDbl instead of Decimal and CDec, depending on your use case.
Well as far as I know an Integer does not save decimals. Use Dim ... As Decimal. Just make life easier

Progress bar with VB.NET Console Application

I've written a parsing utility as a Console Application and have it working pretty smoothly. The utility reads delimited files and based on a user value as a command line arguments splits the record to one of 2 files (good records or bad records).
Looking to do a progress bar or status indicator to show work performed or remaining work while parsing. I could easily write a <.> across the screen within the loop but would like to give a %.
Thanks!
Here is an example of how to calculate the percentage complete and output it in a progress counter:
Option Strict On
Option Explicit On
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "C:\StackOverflow\tabSeperatedFile.txt"
Dim FileContents As String()
Console.WriteLine("Reading file contents")
Using fleStream As StreamReader = New StreamReader(IO.File.Open(filePath, FileMode.Open, FileAccess.Read))
FileContents = fleStream.ReadToEnd.Split(CChar(vbTab))
End Using
Console.WriteLine("Sorting Entries")
Dim TotalWork As Decimal = CDec(FileContents.Count)
Dim currentLine As Decimal = 0D
For Each entry As String In FileContents
'Do something with the file contents
currentLine += 1D
Dim progress = CDec((currentLine / TotalWork) * 100)
Console.SetCursorPosition(0I, Console.CursorTop)
Console.Write(progress.ToString("00.00") & " %")
Next
Console.WriteLine()
Console.WriteLine("Finished.")
Console.ReadLine()
End Sub
End Module
1rst you have to know how many lines you will expect.
In your loop calculate "intLineCount / 100 * intCurrentLine"
int totalLines = 0 // "GetTotalLines"
int currentLine = 0;
foreach (line in Lines)
{
/// YOUR OPERATION
currentLine ++;
int progress = totalLines / 100 * currentLine;
///print out the result with the suggested method...
///!Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach ;)
}
and print the result on the same posititon in your loop by using the SetCursor method
MSDN Console.SetCursorPosition
VB.NET:
Dim totalLines as Integer = 0
Dim currentLine as integer = 0
For Each line as string in Lines
' Your operation
currentLine += 1I
Dim Progress as integer = (currentLine / totalLines) * 100
' print out the result with the suggested method...
' !Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach
Next
Well The easiest way is to update the progressBar variable often,
Ex: if your code consist of around 100 lines or may be 100 functionality
after each function or certain lines of code update progressbar variable with percentage :)

Is possible to ignore the TextBox?

I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.