Java語法基礎練習題和答案:
//1. 編寫一個Java程序,計算并輸出5的階乘。 public class Factorial { public static void main(String[] args) { int num = 5; int factorial = 1; for(int i = 1; i<= num; i++) { factorial *= i; } System.out.println(num + "的階乘是:" + factorial); } }
//2. 編寫一個Java程序,交換兩個變量的值。 public class Swap { public static void main(String[] args) { int a = 5; int b = 10; System.out.println("交換前:a = " + a + ", b = " + b); int temp = a; a = b; b = temp; System.out.println("交換后:a = " + a + ", b = " + b); } }
//3. 編寫一個Java程序,計算并輸出1到100的所有偶數的和。 public class Even { public static void main(String[] args) { int sum = 0; for(int i = 1; i<= 100; i++) { if(i % 2 == 0) { sum += i; } } System.out.println("1到100的所有偶數的和是:" + sum); } }
練習題參考答案:
//1. 5的階乘 = 120 //2. 交換前:a = 5, b = 10;交換后:a = 10, b = 5 //3. 1到100的所有偶數的和是:2550