卡码网Java基础课 | 4. A+B问题IV,5. A+B问题VIII

卡码网Java基础课| 4. A+B问题IV,5. A+B问题VIII

  • 三元运算符
  • 4. A+B问题IV
  • 5. A+B问题VIII

三元运算符

普通if

int a = 10;
int b = 20;
int c;
if (a > b) {c = a;
} else {c = b;
}

而三元运算符的结构如下:
会先求expression的值,如果为 true ,则取值 if-true-statement,否则取值 if-false-statement

{expression} ? if-true-element : if-false-statement;

也就是说

c = a > b ? a : b;

a > b是expression表达式,如果这个表达式的判定结果是 true 的话取a,如果判断结果为 false 的话,则取得 : 后面的值,即 b 的值。

4. A+B问题IV

import java.util.Scanner;public class Main{public static void main(String[] args){Scanner sc = new Scanner(System.in);while(sc.hasNextInt()){int N = sc.nextInt();if(N==0){break;}int sum = 0;for(int i = 0; i < N; i++){sum += sc.nextInt();}System.out.println(sum);}sc.close();}
}

5. A+B问题VIII

import java.util.Scanner;public class Main{public static void main(String[] args){Scanner sc = new Scanner(System.in);while(sc.hasNextInt()){int m = sc.nextInt();int i = 0;while(i++<m){int n = sc.nextInt();int sum = 0;for(int j=0; j<n; j++){sum += sc.nextInt();}System.out.println(sum);if(i<m){System.out.println();}}}}
}