-尝试:
首先,对println语句中的运算规则进行如下尝试性计算:
package com.pancake;
public class Test {
public static void main(String args[]){
int a=3,b=5;
//test1:测试“+”作用
System.out.println("a=");
System.out.println("a="+a);
//test2:测试""作用
System.out.println("");
//test3:组合测试
System.out.println(a+b);
System.out.println("a+b");
System.out.println(a+b+""+a);
System.out.println(a+b+""+a+b);
System.out.println(a+b+"k"+a+b);
System.out.println(a+b+""+a+b);
System.out.println(a+b+""+a*b);
}//of main
}//of class Test
得到如下结果:
a=
a=3
8
a+b
83
835
8k35
835
815
显然,在遇到变量/字符/字符串前,数字之间的加号即为两数相加;遇到后,加号即变成拼接。并且,仅加号会变成拼接,而+,/,%等不会变成拼接。同时应该注意Java运算先后顺序,即要优先选括号里面的内容。
-编写基础运算:
package com.pancake;
public class BasicOperations {
public static void main(String args[]){
int tempFirstInt,tempSecondInt,tempResultInt;
double tempFirstDouble,tempSecondDouble,tempResultDouble;
tempFirstInt = 15;
tempSecondInt = 4;
tempFirstDouble = 1.2;
tempSecondDouble = 3.5;
//Addition
tempResultInt = tempFirstInt + tempSecondInt;
tempResultDouble = tempFirstDouble + tempSecondDouble;
System.out.println("" + tempFirstInt + " + " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " + " + tempSecondDouble + " = " + tempResultDouble);
//Subtraction
tempResultInt = tempFirstInt - tempSecondInt;
tempResultDouble = tempFirstDouble - tempSecondDouble;
System.out.println("" + tempFirstInt + " - " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " - " + tempSecondDouble + " = " + tempResultDouble);
//Multiplication
tempResultInt = tempFirstInt / tempSecondInt;
tempResultDouble = tempFirstDouble / tempSecondDouble;
System.out.println("" + tempFirstInt + " / " + tempSecondInt + " = " + tempResultInt);
System.out.println("" + tempFirstDouble + " / " + tempSecondDouble + " = " + tempResultDouble);
//Modulus
tempResultInt = tempFirstInt % tempSecondInt;
System.out.println("" + tempFirstInt + " % " + tempSecondInt + " = " + tempResultInt);
}//of main
}//of class BasicOperations
最终输出: