James James - 1 year ago 83
Java Question

How to write a calculation using a String and convert the result to a new Double correctly?

I am new to java and have been asked to write a program that males three different types of calculations using three different methods. For the purpose of this question I will provide two examples of comparison. For the method that I am stuck on, the following rules must apply:


  1. Must test that x("12 [ 3") returns null because [ is not a valid operator.

  2. Must be written using the following parameters:

    Double x;
    /*
    * Chops up input on ' ' then decides whether to add or multiply.
    * If the string does not contain a valid format returns null.
    */

    public Double x(String x){
    return new Double(0);
    }



Here is what I have so far along with an example of another calculation which 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 up input on ' ' then decides whether to add or multiply.
* If the string does not contain a valid format returns null.
*/
public Double x(String x){
return new Double(x) + ("[ 3");
}
/*
* Multiplies the parameter x by instance variable x and return the value as a 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 do I make my method which uses a String as a parameter return a new Double value?

  • Since anything can be put into Strings as long as they are within the quotation marks, I would I make java recognize "[" as an invalid operator?



Any help on these issues would be greatly appreciated, thanks.

Answer Source

You get your errors because you try to add Double to String.

Please look at this 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 for example purposes
public static Double x(String x){

    String[] parsed;
    if (x.contains("*")) {
        // * Is a special character in regex
        parsed = x.split("\\*");

        return Double.parseDouble(parsed[0]) * Double.parseDouble(parsed[1]);
    }
    else if (x.contains("+")) {
        // + is again a special character in regex
        parsed = x.split("\\+");

        return Double.parseDouble(parsed[0]) + Double.parseDouble(parsed[1]);
    }

    return null;
}