Java中運算符大抵分為以下六種:
1)算術(shù)運算符:+淹禾,-,*茴扁,/铃岔,%,++峭火,--
2)關(guān)系運算符:>毁习,<,>=卖丸,<=纺且,==,!=----boolean型
3)邏輯運算符:&&稍浆,||载碌,!---- boolean型
4)賦值運算符:=猜嘱,+=,-=嫁艇,*=朗伶,/=,%=
5)字符串連接運算符:+
6)三目/條件運算符:boolean?數(shù)1:數(shù)2
a++的值為a步咪,++a的值為a-1论皆;a+=2相當(dāng)于a=a+2。
int a = 1,b = 2,c = 3;
boolean e1 = (a<b || c++>5);
System.out.println(e1);//true
System.out.println(c);//5猾漫,表示未執(zhí)行c++点晴,||為短路或
boolean e2 = (a>b && c++>5);
System.out.println(e2);//false
System.out.println(c);//5,表示未執(zhí)行c++悯周,&&為短路與
int a = 1,b = 2 ;
int max =a>b?a:b;//此處條件不成立粒督,取數(shù)2為2。
分支結(jié)構(gòu)有以下三種:
1)if結(jié)構(gòu):1條路
if(boolean條件){
? ? 代碼塊
}
2)if...else結(jié)構(gòu):2條路
if(boolean條件){
? ? 代碼塊
}else{
? ? 代碼塊
}
3)if...else if結(jié)構(gòu):多條路
if(boolean條件){
? ? 代碼塊
}else if(boolean條件){
? ? 代碼塊
}else{
? ? 代碼塊
}
4)switch...case結(jié)構(gòu):多條路
優(yōu)點:效率高禽翼、結(jié)構(gòu)清晰
缺點:整數(shù)屠橄、相等
int num = 2;
switch(num){
case 1:代碼塊;break;//break:跳出switch
case 2:代碼塊;break;
}
Scanner scan=new Scanner(System.in);
System.out.println("請輸入年齡:");
int age = scan.nextInt();
scan.close();
System.out.println(age>=18 && age<=50);//判斷輸入的年齡是在【18,50】之間,若是捐康,則true
Scanner scan=new Scanner(System.in);
System.out.println("請輸入年份:");
int year = scan.nextInt();
scan.close();
boolean flag = (year%4==0 && year%100!=0) || year%400;
String str = flag?year+"是閏年":year+"不是閏年";//判斷用戶輸入年份是否是閏年
System.out.println(str);//輸出結(jié)果
Scanner scan=newScanner(System.in);
System.out.println("請輸入單價(¥):");
double unitPrice=scan.nextDouble();
System.out.println("請輸入數(shù)量:");
double amount=scan.nextDouble();
System.out.println("請輸入金額(¥):");
double money=scan.nextDouble();
scan.close();
double totalPrice=0.0;
totalPrice=unitPrice*amount;
if(totalPrice>=500){
totalPrice=totalPrice*0.8;
}
if(money>=totalPrice){
double change=money-totalPrice;
System.out.println("應(yīng)收金額為:¥"+totalPrice+",找零為:¥"+change);
}else{
System.out.println("輸入信息有誤庸蔼!");
}
Scanner scan = new Scanner(System.in);
System.out.println("請輸入成績:");
int score = scan.nextInt();
if(score<0 || score>100){
System.out.println("輸入有誤");
}else if(score>=90){ //score>=0 && score<=100
System.out.println("A-優(yōu)等");
}else if(score>=80){
System.out.println("B-中等");
}else if(score>=60){
System.out.println("C-及格");
}else{
System.out.println("D-差");
}
Scanner scan=newScanner(System.in);
int command=0;
System.out.println("請選擇功能: 1.顯示全部記錄? 2.查詢登錄記錄? 0.退出");
command=scan.nextInt();
scan.close();
switch(command){
case1:System.out.println("顯示全部記錄");break;
case2:System.out.println("查詢登錄記錄");break;
case0:System.out.println("歡迎使用");break;
default:System.out.println("輸入錯誤");
}