JAVA 基础练习题
第一題
1.查看以下代碼,并寫出結果
public class Test01 {public static void main(String[] args) {int i1 = 5;boolean result = (i1++ > 5) && (++i1 > 4);System.out.println(result);System.out.println(i1);}}參考答案:
false
6
認真閱讀上面的程序,我們可以發現,首先定義了一個名為i1的變量,他的值為5,之后使用有表達式(i1++ > 5) && (++ i1 > 4);第一個括號內的內容,自加運算符寫在i1的后面,所以我們運算的順序是應該先比較i1和5的 大小,可以發現這個值為false,之后進行自加運算,所以這時i1的值為6.
同時,我們可以發現,這其中的邏輯運算符使用的是短路與運算符,而運算符前面 的值為false,所以我們不必再運算后面的值,故而最終輸出的結果應該是false和6.
第二題
2.查看以下代碼,并寫出結果
public class Test02 {public static void main(String[] args) {int i1 = 5;boolean result = (i1++ > 5) || (++i1 > 4);System.out.println(result);System.out.println(i1);}}參考答案:
true
7
這道題的考點同樣是短路邏輯運算符.所以同理我們先運算短路邏輯運算符前面部分的表達式:(i1++ > 5),i1的初始值為5,所以他的值不大于5,所以運算結果為false,同時i1要進行自加運算,這時i1的值為6,然后看短路運算符之后的表達式:(++i1 > 4),這時i1的值為6,進行自加運算后,其值為7,7>4,所以運算結果為true.故而最后輸出的值應該是true和7
第三題
請使用三元運算符計算出兩個整數中的最大值。
例如:20 40 打印結果:40是最大值
參考答案:
public class SanYuan {public static void main(String[] args) {int a = 20;int b = 40;int max = a > b ? a : b;System.out.println(max + "是最大值");} }第四題
請使用三元運算符計算出三個整數中的最大值。
例如:20 40 30 打印結果:40是最大值
參考答案:
public class SanYuanPlus {public static void main(String[] args) {int a = 20;int b = 40;int c = 30;int tempmax = a > b ? a : b;int max = tempmax > c ? tempmax : c;System.out.println(max + "是最大值");} }第五題
分析以下需求并實現
1.int類型的變量 成績為鍵盤錄入
2.判斷該學生成績是否及格
3.打印格式:
成績>=60:打印"合格"
成績<60:打印"不合格"
參考答案:
import java.util.Scanner;public class Score{public static void main(String[] args) {Scanner sc = new Scanner(System.in);int score = sc.nextInt();if (score >= 60){System.out.println("成績合格");}else {System.out.println("成績不合格");}} }第六題
分析以下需求并實現
1.功能描述:鍵盤錄入月份,輸出對應的季節
2.要求:
(1)定義一個月份,值通過鍵盤錄入;
(2)輸出該月份對應的季節
3,4,5春季
6,7,8夏季
9,10,11秋季
12,1,2冬季
(3)演示格式如下:
定義的月份:5
控制臺輸出:5月份是春季
參考答案:
import java.util.Scanner;public class Month {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入月份:");int month = sc.nextInt();if (month == 12 || month == 1 || month == 2) {System.out.println("這個月份是冬季");}else if (month >= 3 && month <= 5) {System.out.println("這個月份是春季");}else if (month >= 6 && month <= 8) {System.out.println("這個月份是夏季");}else if (month >= 9 && month <= 11) {System.out.println("這個月份是秋季");}else {System.out.println("輸入的月份不正確");}} }總結
以上是生活随笔為你收集整理的JAVA 基础练习题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pandas删除某列有空值的行_Pyth
- 下一篇: (JAVA)String类之比较方法