I just begin to code on Java simply for fun. I’ve searched for quite a while how I could print the equation (z) itself with the variables. My goal is to see the equation (with the numbers) by using only the variables and not manually typing the thing if I ever change x or y.
I just started and I’m learning from my own, so idk how rookie this is but yeah, i need help.
package learningPackage;
public class LearningScript {
public static void main(String[] args) {
// TODO Auto-generated method stub
int randomNum = (int)(Math.random() * 101);
int x = 100;
int y = 50;
int z = x + y + randomNum;
if (z > 200) {
System.out.println("The result is greater then 200.");
} else {
System.out.println("The result isn't greater then 200.");
}
System.out.println("This is the answer : " + z);
System.out.println("This is the randomized number : " + randomNum);
System.out.print("This is the equation : ");
}
}
The output looks like this at the moment :
The result is greater then 200.
This is the answer : 215
This is the randomized number : 65
This is the equation :
So far, with this code only, I have no errors.
>Solution :
To print the equation you evaluated you can simply do it just like you did it with the other print commands and the variables by.
System.out.println("This is the equation: " + x.toString() + " + " + y.toString() + " + " + randomNumber);
While this is not nice to look at it works.
What it does is:
It appends everything behind the plus sign to the string in front.
The value of x is appended to the string in front, then the string " + ", then the value of y and so on.
An alternative would be to use the String.format() function to format your print-string.
This would look like this:
System.out.println(String.format("This is the equation: %d + %d + %d", x, y, randomNumber))
What it does is, it replaced the %d with the following arguments you passed to the String.format function.
The first one will be replaced with x, the second with y and the third one with randomNumber.
%d is used when you want to display a decimal integer, there are other formatting options.
If you want to explore them, you can take a look here.
https://www.javatpoint.com/java-string-format