Adam3920 Adam3920 - 1 month ago 7
Java Question

How to convert data type of numbers being added together from doubles to string?

For my assignment, I have been asked to create a test harness which provides feedback on whether the following sums are true. For this question, I will only provide one sum as an example. I have been asked to produce the following:


  • TestCalculator has a method called testParser() which:

  • Tests that x("12 + 5") returns a Double with the value 17
    I have been given a template in which to set this out on which looks like this:



Template

public class TestCalculator {
Double x;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
return new Double(0);
}
public void testParsing() {

if (//condition) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}

}


And this is what I've managed to come up with so far:

Current program...Main class

public class Main {

public static void main(String[] args) {

TestCalculator call = new TestCalculator();

call.testParsing();

}
}


TestCalculator class

public class TestCalculator {
Double x;
Double doubleObject = 1.0;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
this.x = 12.0;
x = 5.0;
return new Double(0);
}
public void testParsing() {

if (x(doubleObject) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}

}
}


I have two main queries. Firstly, I have been asked to test if "x("12 + 5") returns a Double with the value 17". I can see that this has been laid out so that the sum is a data type of String and I am confused as to why or how you would perform this calculation using the string data type.

Secondly, Within my current version of the program, the output returns that the adding calculation failed because I cannot access the returned double value of the calculation. But I am unsure of how I would access that value in my if statement and also return the output of the calculation and put it into the Double value that is returned in the method.

I have tried to make the question as clear and concise as possible for the reader to understand, any help on this would be greatly appreciated, thanks.

Answer

to return a new value that adds two values consider

public Double x(Double x){
            System.out.println("== Adding ==");
            //Sum here
            this.x = x;
            return new Double(x + 5);
}

Called as

if (x(12.0) == 17.0) {