John123 John123 - 1 year ago 71
Java Question

How to properly call a String converted to a Double method?

I have created a method which converts a string value into a new Double. I want to create an if statement that tests whether said method returns null which it is suppose to do. This is the code so far:

Content class

public class Content
Double x;

String string = "b";

public void testParsing()
if (//call xMethod == 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)

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;

Main class

public class MainClass {

public static void main(String[] args) {

Content call = new Content();



I know that the following line compiles and outputs as a success: (line 9)

if (x("") == null) {

But I don't think this is doing what I am asking it to do, I am asking it to check if the outcome of the method in which x is pointing to returns null or not. Any clarification on how to properly call this method to check for that condition would be much appreciated, thanks.

Answer Source

But I don't think this is doing what I am asking it to do

You are checking if the result is null. Your logic is correct.

You may want to store the result if you intend on using it later, though.

Double val = x("");
if (val == null) {
    // Invalid
} else {
    System.out.println("Valid! Result: " + val);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download