Richard Newman
Richard Newman

Reputation: 13

Java: Turn a math equation into a String expression?

I'm new to Java and I'm trying to figure out how I would write a math expression that displays the values of the variables on one line, then on the next line does the math?

Here is what I thought would work, but it just prints out the answers instead of the string representations on the top line of the addStuff() method.

public class DoSomeMath {
    int num1C = 3;
    int num1A = 7;
    public void addStuff(){
        //Show the Equation//
        System.out.println("Adding num1C + num1A: " + Integer.toString(num1C) + Integer.toString(num1A));
        //Show the Answer//
        System.out.println("Adding num1C + num1A: " + num1C + num1A);
    }
}

Upvotes: 1

Views: 2932

Answers (5)

GreySage
GreySage

Reputation: 1180

Try making it + Integer.toString(num1C) + " + " + Integer.toString(num1A)

Any static characters you can enter as a string, and then concatenate with the variables.

Upvotes: 0

stbamb
stbamb

Reputation: 197

Try this:

public class DoSomeMath {
    int num1C = 3;
    int num1A = 7;
    public void addStuff(){
        //Show the Equation//
        System.out.println("Adding num1C + num1A: " + num1C + " + " + num1A);
        //Show the Answer//
        System.out.println("Adding num1C + num1A: " + (num1C + num1A));
    }
}

Upvotes: 0

Corey Hoffman
Corey Hoffman

Reputation: 143

Achieving the effect you want for this is even easier than you are making it:

//Show the Equation//
System.out.println("Adding num1C + num1A: " + num1C + "+" + num1A);
//Show the Answer//
System.out.println("Adding num1C + num1A: " + (num1C + num1A));

The first line concatenates them as strings, while the second line forces the integer addition via parenthesis.

Upvotes: 0

Sean N.
Sean N.

Reputation: 973

Your num1C and num1A are getting converted to Strings and appended as Strings. Use parentheses so the math happens first, then the String append last.

System.out.println("Adding num1C + num1A: " + (num1C + num1A));

Upvotes: 0

Vinayak Pingale
Vinayak Pingale

Reputation: 1315

You are using a + operator in System.out.println(String str) When you use + sign for string's it normally does the task of appending the string in the string pool.

//Show the Equation//
System.out.println("Adding num1C + num1A: " + Integer.toString(num1C) + 
"+"+ Integer.toString(num1A));
//Show the Answer//
System.out.println("Adding num1C + num1A: " + " " + (num1C + num1A));

So understand the use of + arithmetic operator with Strings and integer value.

Upvotes: 2

Related Questions