java中非法运算符_Java 中的运算符和流程控制相关内容的理解
//三元表達式的嵌套
int max = i > j ? (i > k ? i : k) : (j > k ? j : k);
//練習:輸出分數所對應的等級 >=90 -A >=80 -B >=70 -C >=60 -D <60 -E
char level = score >= 90 ? 'A':(score >= 80 ? 'B' : (score >= 70 ? 'C' : (score >=60 ? 'D' : 'E')));
System.out.println(level);
擴展:從控制臺獲取數據
import java.util.Scanner;
Scanner s = new Scanner(System.in);
int i = s.netInt(); //獲取整數
double d = s.nextDouble(); //獲取小數
String str = s.next();
>= 大于等于? ? ? >>= 右移等于
10 >= 2? ? -> true
10 >>= 2? ?->i = i >> 2;? -> 2
運算符的優先級
~!? ? 算術(++? --? *? /? %? +? - )? <>? >>>? ? 關系? ? 邏輯&? | ^? ? 三元? ? 賦值
一元??? ? ???? ??? ??? ??? ??? ??? ??? ??? ?? ? 二元運算
(一元的幾個運算符的優先級是一樣的)
流程控制
順序結構:指代碼從上到下從左到右來依次編譯運行的
分支結構:
判斷結構
if(邏輯值){
代碼塊
}
執行順序:先執行邏輯值,如果邏輯值為 true,那么執行 代碼塊。
注意:如果 if 中的代碼塊只有 1 句話,那么可以省略 {} 不寫
if(邏輯值){
Code1;
}else{
Code2;
}
練習:
1.輸入三個數字,獲取三個數字中的最小值
import java.util.Scanner;
public class IfElseExer {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int i = s.nextInt();
int j = s.nextInt();
int k = s.nextInt();
/*
if(i < j){
if(i < k){
System.out.println(i);
} else {
System.out.println(k);
}
} else {
if(j < k){
System.out.println(j);
} else {
System.out.println(k);
}
}
*/
int min = i;
if(min > j)
min = j;
if(min > k)
min = k;
System.out.println(min);
}
}
2.輸入一個數字表示重量,如果重量<=20,則每千克收費 0.35 元;如果超過 20 千克不超過 100 千克的范圍,則超過的部分按照每千克 0.5 元收費;如果超過 100 千克,則超過的范圍按照每千克 0.8 元收費。
import java.util.Scanner;
public class IfElseExer2 {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
double weight = s.nextDouble();
double price = 0;
if(weight < 0){
System.out.println("不合法的重量!!!");
} else {
if(weight <= 20){
price = weight * 0.35;
} else {
if(weight <= 100){
price = 20 * 0.35 + (weight - 20) * 0.5;
} else {
price = 20 * 0.35 + 80 * 0.5 + (weight - 100) * 0.8;
}
}
}
System.out.println(price);
}
}
或者
import java.util.Scanner;
public class IfElseIfDemo {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
double weight = s.nextDouble();
double price = 0;
if(weight < 0){
System.out.println("非法的重量!!!");
} else if(weight <= 20){
price = weight * 0.35;
} else if(weight <= 100){
price = 7 + (weight - 20) * 0.5;
} else {
price = 47 + (weight - 100) * 0.8;
}
System.out.println(price);
}
}
if(邏輯值1){
Code1;
}else if(邏輯值2){
Code2;
}
練習:
輸入一個數字表示月份,然后輸出這個月份所對應的季節。 3 - 5 -春? ? 6 - 8 - 夏? ? 9 - 11 - 秋? ? 12、1、2 - 冬
import java.util.Scanner;
public class IfElseIfExer {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int month = s.nextInt();
if(month < 1 || month > 12){
System.out.println("Illegal month !!!");
} else if(month > 2 && month < 6){
System.out.println("Spring");
} else if(month > 5 && month < 9){
System.out.println("Summmer");
} else if(month > 8 && month < 12){
System.out.println("Autumn");
} else {
System.out.println("Winter");
}
}
}
選擇結構
循環結構:
總結
以上是生活随笔為你收集整理的java中非法运算符_Java 中的运算符和流程控制相关内容的理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java数据库面试题
- 下一篇: Java数据库异常