简体   繁体   English

Java:将数学方程式转换为String表达式吗?

[英]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? 我是Java的新手,我想弄清楚如何编写一个数学表达式来在一行上显示变量的值,然后在下一行进行数学运算?

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. 这是我认为可行的方法,但是它只是打印出答案,而不是在addStuff()方法顶行显示字符串表示形式。

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);
    }
}

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. 您正在System.out.println(String str)中使用+运算符。当对字符串使用+符号时,通常会执行将字符串追加到字符串池中的任务。

//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. 因此,请理解将+算术运算符与字符串和整数值一起使用。

Try making it + Integer.toString(num1C) + " + " + Integer.toString(num1A) 尝试使其+ Integer.toString(num1C) + " + " + Integer.toString(num1A)

Any static characters you can enter as a string, and then concatenate with the variables. 您可以将任何静态字符作为字符串输入,然后将其与变量连接。

Your num1C and num1A are getting converted to Strings and appended as Strings. 您的num1C和num1A将转换为字符串并附加为字符串。 Use parentheses so the math happens first, then the String append last. 请使用括号,以便首先进行数学运算,然后最后进行字符串附加运算。

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

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. 第一行将它们连接为字符串,而第二行通过括号强制整数加法。

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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM