How do you make java accept a string equation as a double? - java

For my algebra project I am making a java program that can graph an equation you type in. I got free basic graphing code from a website, and implemented a couple things. In the code, when it returns the equation for the graph, it is a double. In the code, you can change the equation in the double and it will graph it fine. When I try to put my string in the code(from user input) the program will crash if i put anything like X or * or / in the equation. I tried to put (Double.parseDouble(equation)) in the double, but it still doesn't work. BTW i am new at java. Thanks!
This is what the code looks like(class "circle1"):
public double getY(double x) {
return (Double.parseDouble(equation));
}
In the class that reads the equation, here is the code:
graph.functions.add(new Circle1());
(equation is the string)

If you are allowed to use libraries http://code.google.com/p/symja/wiki/MathExpressionParser may be what you are looking for

Double.parseDouble() can only parse double values. For example if your string value is "5" , "5.0" or "5.89", Double.parseDouble() won't throw an exception.
If you want to parse an equation, you will have to parse it using your own logic. For example you will have to search for operators (like +,-,/) , split the string on them and then process the input.

Related

Having issue with a very simple java program, not displaying proper result

here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.

Write a Java Program That Allows Users to Input Their Own Formula and Calculates It

I am trying to write a java program (which is part of an assignment) which allows users to input their own function, and then the program calculates it and gets a value.
I have actually written a program that calculates an IVP (Initial Value Problem) using the Euler-Cauchy method. My initial function was -2*t*u^2.
However, what if I want to work on 4*t*u^3 instead or some other formula?
I tried getting the formula as String from the user, but I am having difficulty in matching a particular variable (e.g. t or u) to a number.
Use the String.replace() function to convert the u and t from the formula string to the actual variables, then take a good look at this Stack Overflow question: Convert String to Code

I am running JAVA. When I try to create this method i get errors. The IDE told me to use an array I did and it still didnt work

I created the method below but it has red lines under it in netBeans. the IDE told me to use an array and that still didnt work so i went back to this.
private double getPaymentAmount(double loanValue, double paymentAmount, double numOfPayments, double periodInterestRate){
paymentAmount = loanValue [periodInterestRate(1+periodInterestRate)^numOfPayments]/[(1+periodInterestRate)^numOfPayments-1];
return paymentAmount;
You're confusing Java syntax with mathematical notation. While you might try to multiply variables as someVar(someVar2+someVar3) that's actually a method call. Additionally, square brackets have special meaning, and ^ is XOR and not power (use Math.pow instead).
loanValue *
(periodInterestRate * Math.pow(1+periodInterestRate, numOfPayments)) /
(Math.pow(1+periodInterestRate, numOfPayments)-1);
The code above has been revised to be syntactically valid. I've also taken the liberty of splitting it over multiple lines to make it more readable. However, because your original code was extremely unclear, it is possible that the mathematical meaning of my expression is different from your intention. I'm assuming that you intended to write the following:
Also, you declare paymentAmount as a parameter, although it is not a parameter, but rather a return value.
private double getPaymentAmount(double loanValue, double numOfPayments, double periodInterestRate) {
double paymentAmount = loanValue *
(periodInterestRate * Math.pow(1+periodInterestRate, numOfPayments)) /
(Math.pow(1+periodInterestRate, numOfPayments)-1);
return paymentAmount;
}
What is this syntax with loanValue [calculation1]/[calculation2]?:
paymentAmount = loanValue[periodInterestRate(1+periodInterestRate)^numOfPayments]/[(1+periodInterestRate)^numOfPayments-1];
This does not look like correct use of [] and if loanValue is a function maybe it should be more like:
paymentAmount = loanValue(periodInterestRate((1+periodInterestRate)^numOfPayments)/((1+periodInterestRate)^numOfPayments-1));
Or if loanValue is an array then maybe:
paymentAmount = loanValue[periodInterestRate(1+periodInterestRate)^numOfPayments]/((1+periodInterestRate)^numOfPayments-1);
But it is hard to believe that
periodInterestRate(1+periodInterestRate)
would match an array index or even a hash key.
Then maybe loanValue is just a number, as some others have suggested.
Please clarify: What is the type of loanValue?
Thanks
Square brackets don't mean the same thing as they do in math.Nethier does the caret. Caret is XOR. I think this is what you want:
loanValue * (Math.pow(periodInterestRate(1+periodInterestRate), numOfPayments)) / (Math.pow(1+periodInterestRate, numOfPayments-1))

Convert a string into mathematical equation?

I'm a beginner. I want to convert a string into a mathematical equation in order to be the input of my graphic calculator
for example:
cos(x+1)+ ln(x)
so we will convert it to
double x = -10;
for (int i=0; i<100; i++) {
double y=Math.cos(x+1)+Math.log(x)
x=x+0.5
}
so I want to know a method of converting y
Thank You
There is no "out-of-the-box" solution in java for this.
However:
Obligatory answer: google -> "convert string to mathematical expression java" first few answers are pretty good (like: What's a good library for parsing mathematical expressions in java? )
Obligatory answer 2: There are quite a few libraries on the net for converting strings into math expressions, naming them would be off-topic according to the rules, so I suggest "Obligatory answer" first few hits.
Also most likely you are better off by choosing a Format you will receive, and write your own parser for that format.
You need to write a parser first, building a tree of your input expression. You can then use that to generate your code.
But, "I'm a beginner" doesn't go well with writing parsers :)
You need to have a small formal grammar describing the syntax of your expression, then you need to convert your input string expression to an AST representation.
http://en.wikipedia.org/wiki/Abstract_syntax_tree
Finally you need to have a procedure to evaluate the AST for certain values of the parameters.
This is not a simple thing to do in pure Java. There are a lot of other similar questions with good answers here. Most of the solutions have to do with evaluating the expression in an interpreter or parsing the expression (there are some libraries available for this), or even shelling out. I don't know what is available in Android specifically to do this but there are tons of good answers for this in SO. Here is a good one to start with: Evaluating a math expression given in string form
I did that exact thing using NCalc. I passed in the user's string expression, replaced the variables with the values I am evaluating at, then using the Evaluate method and parsing to a double.
private double Function(double t, double y)
{
NCalc.Expression expression = new NCalc.Expression(this.Expression);
expression.Parameters["t"] = t;
expression.Parameters["y"] = y;
double value;
double.TryParse(expression.Evaluate().ToString(), out value);
return value;
}
For example, given the inputs t = .5 and y = 1 and the expression "4*y + Tan(2*t)", we would evaluate the string "4*1 + Tan(2*.5)" using NCalc.
It is not perfect, NCalc throws an exception if it cannot parse the user's string or it the datatypes of functions are different. I am working on polishing it.
I also asked the same question here.

Determining input for Overloaded Method

I'm running into a bit of an issue with determining if the user input is an int or double.
Here's a sample:
public static int Square(int x)
{
return x*x;
}
public static double Square(double x)
{
return x*x;
}
I need to figure out how to determine based on the Scanner if the input is a int or double for the above methods. However since this is my first programming class, I'm not allowed to use anything that hasn't been taught - which in this case, has been the basics.
Is there anyway of possibly taking the input as a String and checking to see if there is a '.' involved and then storing that into an int or double?
Lastly, I'm not asking for you to program it out, but rather help me think of a way of getting a solution. Any help is appreciated :)
The Scanner has a bunch of methods like hasNextInt, hasNextDouble, etc. which tell you whether the "next token read by the Scanner can be interpreted as a (whatever)".
Since you mentioned you've learned about the Scanner object, I assume the methods of that class are available to you for your use. In this case, you can detect if an input is an integer, double, or just obtain an entire line. The methods you would most be interested here would be the hasNextDouble() method (returns a boolean indicating whether or not the current token in the Scanner is actually a double or not) and the nextDouble() method (if the next token in the Scanner is in fact a double, parse it from the Scanner as one). This is probably the best direction for determining input types from a file or standard input.
Another option is to use the wrapper classes static methods for converting values. These are generally named like Integer.parseInt(str) or Double.parseDouble(str) which will convert a given String object into the appropriate basic type. See the Double classes method pasrseDouble(String s) for more details. It could be used in this way:
String value = "123.45"
double convertedValue = 0.0;
try {
convertedValue = Double.parseDouble(value);
} catch (NuberFormatException nfe) {
System.err.println("Not a double");
}
This method is probably best used for values that exist within the application already and need to be verified (it would be overkill to construct a Scanner on one small String for this purpose).
Finally, yet another potential (but not very clean, straightforward, or probably correct technique) could be looking at the String object directly and trying to find if it contains a decimal point, or other indicators that it is in fact a double. You may be able to use indexOf(String substr) to determine if it appears in the String ever. I suspect this method has a lot of potential problems though (say for example, what if the String has multiple '.' characters?). I wouldn't suggest this route because it is error prone and hard to follow. It might be an option if that's what the constraints are, however.
So, IMHO, your options should go as follow:
Use the Scanner methods hasNextDouble() and nextDouble()
Use the wrapper class methods Double.parseDouble(String s)
Use String methods to try and identify the value (avoid this technique at all costs if either of the above options are available).
Since you think you won't be allowed to use the Scanner methods there are a number of alternatives you try. You mentioned checking to see if a String contains a .. To do this you could use the contains method on String.
"Some words".contains("or") // evaluates to true
The problem with this approach is that there are many Strings that contain . but aren't floating point numbers. For examples, sentences, URLs and IP addresses. However, I doubt you're lecturer is trying to catch you out with and will probably just be giving you ints and doubles.
So instead you could try casting. Casting a double to an int results in the decimal portion of the number being discarded.
double doubleValue = 2.7;
int castedDoubleValue = (int) doubleValue; // evaluates to 2
double integerValue = 3.0;
int castedIntegerValue = (int) integerValue; // evaluates to 3
Hopefully, that should be enough to get you started on writing a solution to the problem.
Can be checked like this
if(scanner.hasNextDouble()}
{
System.out.println("Is double");
}
if(scanner.hasNextDouble()}
{
System.out.println("Is double");
}

Categories

Resources