java - How to write a calculation using a String and convert the result to a new Double correctly? -
i new java , have been asked write program males 3 different types of calculations using 3 different methods. purpose of question provide 2 examples of comparison. method stuck on, following rules must apply:
- must test x("12 [ 3") returns null because [ not valid operator.
must written using following parameters:
double x; /* * chops input on ' ' decides whether add or multiply. * if string not contain valid format returns null. */ public double x(string x){ return new double(0); }
here have far along example of calculation works fine:
testcalculator class
public class testcalculator { double x; string string = "b"; double doubleobject = 1.0; double doubleprimitive = 2; public void testparsing() { if (multiplyx(12.0) == 60) { system.out.println("multiplying success");} else { system.out.println("multiplying fail"); } if (x("12") == null) { system.out.println("ovalid operator success");} else { system.out.println("invalid operator fail"); } } /* * chops input on ' ' decides whether add or multiply. * if string not contain valid format returns null. */ public double x(string x){ return new double(x) + ("[ 3"); } /* * multiplies parameter x instance variable x , return value double. */ public double multiplyx(double x){ system.out.println("== multiplying =="); this.x = x; return new double(x * 5); } }
main class
public class main { public static void main(string[] args) { testcalculator call = new testcalculator(); call.testparsing(); } }
my main queries are:
- how make method uses string parameter return new double value?
- since can put strings long within quotation marks, make java recognize "[" invalid operator?
any on these issues appreciated, thanks.
you errors because try add double string.
please @ example:
public static void main(string[] args) { system.out.println(x("12 + 3")); system.out.println(x("12 * 3")); system.out.println(x("12 [ 3")); } // static example purposes public static double x(string x){ string[] parsed; if (x.contains("*")) { // * special character in regex parsed = x.split("\\*"); return double.parsedouble(parsed[0]) * double.parsedouble(parsed[1]); } else if (x.contains("+")) { // + again special character in regex parsed = x.split("\\+"); return double.parsedouble(parsed[0]) + double.parsedouble(parsed[1]); } return null; }
Comments
Post a Comment