1.“&”和“&&”的异同
//区分& 与 &&
//相同点①: & 与 && 的运算结果相同
//相同点②: 党符号左边是true时,二者都会执行符号右边的运算
//不同点:当符号左边是false时,&继续执行符号右边的运算,&&不再执行符号右边的运算
//开发中:推荐使用&&
2.程序输出:
程序:
public class EverydayTest2 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
short z = 40;
if((z++==40)&&(b=true))z++;
if((a=false)||(++z==43))z++;
System.out.println("z="+z);
}
}
输出:
z=44
3.定义三个int型变量并赋值,使用三元运算符或者if-else获取这三个数中较大数的实现。
三元运算符:
int n1 = 12;
int n2 = 30;
int n3 = -43;
int max1 = (n1>n2)?n1:n2;
int max2 = (max1>n3)?max1:n3;
System.out.println("三个数中的最大值为:"+max2);
输出:
三个数中的最大值为:30
if-else结构:
public class EverydayTest2 {
public static void main(String[] args) {
int a=10,b=21,c=-21;
int max;
if(a>=b && a>=c){
max=a;
}else if(b>=a && b>=c){
max=b;
}else{
max=c;
}
System.out.println("三个数中的最大值为:"+max);
}
}
输出:
三个数中的最大值为:21
4.编写程序,声明2个double型变量并赋值,判断第一个数大于10.0,切4且第2个数小于20.0,打印两数之和,否则,打印两束之差。
public class EverydayTest2 {
public static void main(String[] args) {
double d1 = 12.3;
double d2 = 32.1;
if(d2 >10 && d2<20) {
System.out.println(d1+d2);
}else {
System.out.println(d2-d1);
}
}
}
输出:
19.8
5.交换两个变量值的代码的实现
public class EverydayTest2 {
public static void main(String[] args) {
String s1 = "北京";
String s2 = "南京";
String temp = s1;
s1=s2;
s2=temp;
System.out.println("s1="+s1+"\ns2="+s2);
}
}
输出:
s1=南京
s2=北京
这篇博客探讨了Java编程中`&`和`&&`运算符的区别,强调在开发中推荐使用`&&`。程序示例展示了条件控制的运用,包括三元运算符和if-else结构来寻找最大值。还涵盖了如何根据条件判断打印两个数的和或差,并演示了字符串变量的交换过程。
179

被折叠的 条评论
为什么被折叠?



