三元運算符
格式:關系表達式?表達式1:表達式2;
計算規則:
首先計算? 關系表達式,如果值為true ,表達式1的值就是運算結果。
如果為false,表達式2的值就是運算結果
//定義兩個變量
int a =10;
int b =20;
//獲取兩個數據中的最大值
int max = a > b ? a : b;//如果a大于b為真,則把a賦值給max,為false是則把b賦值給max
//輸出結果
System.out.println("max:"+max);
任務要求 兩個物體分別為180kg,200kg。判斷兩個物體重量是否一樣。
int a =180;
int b =200;
boolean weight = a==b ?true :false;
System.out.println("weight:"+weight);
150 210 165求最高值?
int a =150;
int b =210;
int c =165;
int weight = a>b ? a :b;
int weight2 = weight>c ?weight : c;
System.out.println("max:"+weight2);
數據輸入
scanner?
import java.util.Scanner;
public class He {
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
//輸入數據
? ? ? ? int x = sc.nextInt();
//輸出數據
? ? ? ? System.out.println("x:"+x);
}
}
輸入體重
Scanner sc =new Scanner(System.in);
//輸入數據
System.out.println("請輸入三個數值:");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int g = a>b? a : b;
int max =g>c? g:c;
//輸出數據
System.out.println("最大值:"+max);
流程控制?
順序結構,分支結構(if,switch),循環結構(for,while,do...while)
順序結構,按照代碼先后順序依次執行。
if語句
int a =10;
int b =20;
int c =10;
//需求判斷a和b的值是否相等,如果相等就在控制臺輸出 a等于b
? if (a==b){
System.out.println("a等于b");
}
if (a==c){
System.out.println("a等于c");
}
int a =10;
int b =20;
int c =10;
//需求判斷a和b的值是否相等,如果相等就在控制臺輸出 a等于b
? if (a==b){
System.out.println("a等于b");
}else{
System.out.println("a不等于b");
}
if (a==c){
System.out.println("a等于c");
}
判斷奇偶數
Scanner number =new Scanner(System.in);
System.out.println("請輸入一個整數");
int num = number.nextInt();
if (num%2==0){
System.out.println(num+"是偶數");
}else {
System.out.println(num+"是奇數");
}
周一至周日:
Scanner number =new Scanner(System.in);
System.out.println("請輸入一個星期數(1-7):");
int week =number.nextInt();
if (week==1){
System.out.println("星期一");
}else if (week ==2){
System.out.println("星期二");
}else if (week ==3){
System.out.println("星期三");
}else if (week ==4){
System.out.println("星期四");
}else if (week ==5){
System.out.println("星期五");
}else if (week ==6){
System.out.println("星期六");
}else if (week ==7){
System.out.println("星期天");
}
考試成績 90-100 A 80-89 B? 70-79 C 60-69 D
Scanner number =new Scanner(System.in);
System.out.println("請輸入分數:");
int score =number.nextInt();
if (score>=90&&score<=100){
System.out.println("A");
}else if (score>=80&&score<=89){
System.out.println("B");
}else if (score>=70&&score<=79){
System.out.println("C");
}else if (score>=60&&score<=69){
System.out.println("D");
}else if (score>100||score<0){
System.out.println("請重新輸入分數");
}
switch語句
Scanner number =new Scanner(System.in);
System.out.println("請輸入數字1-7:");
int week = number.nextInt();
switch (week){
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期天");
break;
default:
System.out.println("你輸入的星期有誤!");
}