public static void main(String[] args) {
//Numbers
int operand1 = 25;
int operand2 = 6;
//Arithmetic values
int sum = 0;
int difference = 0;
int product = 0;
int quotient = 0;
int remainder = 0;
//Operations
sum = operand1 + operand2;
difference = operand1 - operand2;
product = operand1*operand2;
quotient = operand1/operand2;
remainder = operand1%operand2;
//Output
System.out.println("Arithmetic");
System.out.println("============================");
System.out.println("25 + 6 = " + sum);
System.out.println("25 - 6 = " + difference);
System.out.println("25 * 6 = " + product);
System.out.println("25 / 6 = " + quotient);
System.out.println("25 % 6 = " + remainder);
我试图找到替换" 25 + 6"," 25 - 6"等等的方法...... (operand1" +" operand2" =" sum)因此值会根据我在oeprand1和operand2上的值而动态变化。有没有办法做到这一点?感谢
答案 0 :(得分:5)
您执行此操作的方式与将结果变量插入字符串的方式完全相同...
System.out.println(operand1 + " + " + operand2 + " = " + sum);
如果您愿意,也可以使用printf
,但必须明确插入换行符:
System.out.printf("%d + %d = %d%n", operand1, operand2, sum);
答案 1 :(得分:1)
也许只是我,但我发现这看起来更清洁。
System.out.print(MessageFormat.format(
"Arithmetic\n" +
"============================\n"+
"{0} + {1} = {2}\n"+
"{0} - {1} = {3}\n"+
"{0} * {1} = {4}\n"+
"{0} / {1} = {5}\n"+
"{0} % {1} = {6}\n", operand1,operand2,sum,difference,product,quotient,remainder));
MessageFormat.format
提供了一种完美的替代方式来完成您所寻找的目标。
请记住有时 less 更多!为什么一遍又一遍地重复打印命令?