2012年3月4日 星期日

學習範例 1_4:亂數的應用

猜猜你今天的幸運數字,運用亂數產生器,編寫,會產生幸運數字(1~9)的程式。

import java.util.Random;

class Ex1_4 {

    public static void main(String[] args) {
        Random rand = new Random();

        int luckyNo = 1 + rand.nextInt(8);

        System.out.println("今日的幸運數字為 " + luckyNo + "。");
    }
}

執行結果。



2012年3月3日 星期六

jAG109

class MyAG109{

public static void main(String[] args){
final int x = 5;
int y = 3;

System.out.println("x + y = " + (x + y));

x = 6;
y = 9;

System.out.println("x + y = " + (x+y));
}

}


final 變數的運用,有幾個編譯憤怒?

學習範例 final 變數的運用

計算圓的周長和面積(使用final變數表示圓周率)

class Ex1_3 {

    public static void main(String[] args){
        final double PI = 3.1416;
        int radius = 3;

        System.out.println("圓周長 = " + 2 * PI * radius + "。");
        System.out.println("圓面積 = " + PI * radius* radius + "。");
    }
}

執行結果。

2012年3月1日 星期四

練習題 1_2:計算梯型面積

計算梯形的面積,由鍵盤輸入 長底、下底、高,三個實數 。

輸出結果, 如下。

程式碼,如下。

import java.util.Scanner;

public class P1_2 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("求出梯形的面積");
        System.out.println("--------------");
       
        System.out.print("上底 : ");
        double x = scanner.nextDouble();
        System.out.print("下底 : ");
        double y = scanner.nextDouble();
        System.out.print("高   : ");
        double h = scanner.nextDouble();

        double a = (x + y) * h / 2;

        System.out.println("面積為  " + a);
    }
}

學習範例 1_2:由鍵盤輸入變數並運算

由鍵盤輸入二個實數,並且將其加減乘除後的結果輸出(double)。


import java.util.Scanner;

class Ex1_2 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("請輸入X:");
        double x = scanner.nextDouble();

        System.out.print("請輸入Y:");
        double y = scanner.nextDouble();

        System.out.println("x + y = " + (x + y));
        System.out.println("x - y = " + (x - y));
        System.out.println("x * y = " + (x * y));
        System.out.println("x / y = " + (x / y));
        System.out.println("x % y = " + (x % y));
    }
}

執行結果。

2012年2月29日 星期三

學習範例 1_1:變數的初始化及基本運用

簡單的加法運算 。


class Ex1_1 {
    public static void main(String[] args) {
        int x = 63;
int y = 37;
  int result = x + y;

System.out.println(x + "+" + y + "=" + result);
     }
}

執行結果。

jAG108

class MyAG108 {

public static void main(String[] args) {
int x; // x為int型態的變數
int y; // y為int型態的變數

System.out.println("x的值為" + x + "。");                   // 顯示x的值
System.out.println("y的值為" + y + "。");                // 顯示y的值
System.out.println("x+y的和為" + (x + y) + "。");        // 顯示x+y的和
System.out.println("x及y的平均值為" + (x + y) / 2 + "。");  // 顯示平均值
}
}



小程式,幾個編譯憤怒?