1.定义三个int型变量并赋值,使用三元运算符或者if-else获取三个数中较大数的实现。
//法一:
class MaxNum{
public static void main(String[] args){
int x = 10;
int y = 21;
int z = 5;
int max1 = (x > y)? x : y;
int max2 = (max1 > z)? max1 : z;
System.out.println("三个数中最大的数为:" + max2);
}
}
//法二:
class MaxNum1{
public static void main(String[] args){
int x = 10;
int y = 21;
int z = 5;
int max;
if(x >= y && x >= z)
max = x;
else if(y >= z && y >= z)
max = y;
else
max = z;
System.out.println("三个数中最大的数是:" + max);
}
}
2.编写程序,声明2个double型变量并赋值。判断第一个数大于10.0,且第2个数小于20.0,打印两数之和。否则,打印两数的乘积。
class JudgeNum{
public static void main(String[] args){
double d1 = 12.3;
double d2 = 32.1;
if(d1 > 10.0 && d2 < 20.0)
System.out.println(d1 + d2);
else
System.out.println(d1 * d2);
}
}
3.交换两个变量值的代码实现
class SwapVar{
public static void main(String[] args){
String s1 = "橘子";
String s2 = "橙子";
String temp;
temp = s1;
s1 = s2;
s2 = temp;
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
}
}