1. 程式人生 > >Java經典小案例(不定時更新)

Java經典小案例(不定時更新)

人類除了擅長頹廢,做什麼都不對

1. 實現金字塔效果

這裡寫圖片描述 這裡寫圖片描述

import java.util.Scanner;

/**
 * @author caojiantao-ext 根據輸入的數目輸出金字塔
 */
public class _01 {

    public static void main(String[] args) {
        System.out.print("請輸入金字塔層數:");
        Scanner scanner = new Scanner(System.in);
        int count = scanner.nextInt();
        System.out
.print("1:金字塔;2:倒金字塔:"); int mode = scanner.nextInt(); switch (mode) { case 1: function_1(count); break; case 2: function_2(count); break; default: System.out.println("輸入有誤!"); break; } scanner.close(); } // 金字塔
public static void function_1(int count) { for (int i = 0; i < count; i++) { for (int space = count - i - 1; space > 0; space--) { System.out.print(" "); } for (int star = 0; star < (2 * i + 1); star++) { System.out
.print("☆"); } System.out.println(); } } // 倒金字塔 public static void function_2(int count) { for (int i = 0; i < count; i++) { for (int space = 0; space < i; space++) { System.out.print(" "); } for (int star = 0; star < (2 * (count - i) - 1); star++) { System.out.print("☆"); } System.out.println(); } } }

2. 顯示九九乘法表

這裡寫圖片描述

/**
 * @author caojiantao-ext 九九乘法表
 */
public class _02 {

    public static void main(String[]args){
        for (int row = 1; row < 10; row++) {
            for (int column = 1; column <= row; column++) {
                System.out.print(row+"*"+column+"="+row*column);
                System.out.print("    ");
            }
            System.out.println();
        }
    }
}

3.繪餘弦正弦函式

這裡寫圖片描述

import java.applet.*;
import java.awt.Graphics;

/**
 * @author caojiantao-ext 畫餘弦函式
 */
public class _03 extends Applet {

    /**
     * 重寫resize函式,改變applet窗體大小
     */
    @Override
    public void resize(int arg0, int arg1) {
        // TODO Auto-generated method stub
        super.resize(800, 600);
    }

    /**
     * 重寫paint,畫點成線,特別注意比例的轉換(自己計算)
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        // 畫x軸
        g.drawLine(50, 300, 750, 300);
        // 畫y軸
        g.drawLine(400, 50, 400, 550);
        // 畫座標軸箭頭
        g.drawLine(735, 290, 750, 300);
        g.drawLine(735, 310, 750, 300);
        g.drawLine(390, 65, 400, 50);
        g.drawLine(410, 65, 400, 50);
        // 計算縮放比例
        double d = 150.0 / (Math.PI);
        // 畫cos曲線
        int x, y;
        for (x = 100; x <= 700; x++) {
            // 特別注意這裡的sin(PI)不等於0,浮點通病
            double a = Math.sin((x - 400) / d);
            // 繪餘弦函式
            // double a = Math.cos((x - 400) / d);
            y = (int) (a * d);
            // 注意座標轉換
            g.drawString("·", x, 300 - y);
        }
    }
}

4.繪奧運五環

這裡寫圖片描述

import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 * @author caojiantao-ext 畫奧運五環
 */
public class _04 extends Applet {

    @Override
    public void resize(int width, int height) {
        // TODO Auto-generated method stub
        super.resize(400, 300);
    }

    @Override
    public void paint(Graphics g) {
        // TODO Auto-generated method stub
        super.paint(g);
        // clr[]儲存顏色
        Color clr[] = { Color.blue, Color.black, Color.red, Color.yellow, Color.green };
        // x[]儲存起始x座標
        int[] x = { 85, 165, 245, 125, 205 };
        // y[]儲存起始y座標
        int[] y = { 70, 70, 70, 135, 135 };
        // 設定畫筆的粗細
        ((Graphics2D) g).setStroke(new BasicStroke(5.0f));
        for (int loop = 0; loop < clr.length; loop++) {
            g.setColor(clr[loop]);
            // 注意x,y是外切矩形的起始座標,假設半徑為90
            g.drawOval(x[loop], y[loop], 90, 90);
        }
    }
}

4.輸出楊輝三角

這裡寫圖片描述

import java.util.Scanner;

/**
 * @author caojiantao-ext 楊輝三角
 */
public class _05 {

    // 寫內層迴圈時注意控制範圍
    public static void main(String[] args) {
        System.out.print("請輸入楊輝三角的行數:");
        Scanner scanner = new Scanner(System.in);
        int count = scanner.nextInt();
        int num[][] = new int[count][count];
        // 預防陣列越界,初始化首列的值
        for (int loop = 0; loop < count; loop++) {
            num[loop][0] = 1;
        }
        // 根據楊輝三角的規則,給二維陣列賦值處理
        for (int row = 1; row < count; row++) {
            for (int column = 1; column <= row; column++) {
                num[row][column] = num[row - 1][column] + num[row - 1][column - 1];
            }
        }
        // 迴圈列印
        for (int row = 0; row < count; row++) {
            for (int i = 0; i < 2 * (count - row) - 1; i++) {
                System.out.print(" ");
            }
            for (int column = 0; column <= row; column++) {
                // 輸出控制,完美等腰
                System.out.printf("%-4d", num[row][column]);
            }
            System.out.println();
        }
        scanner.close();
    }
}

6.繪畫國際棋盤

這裡寫圖片描述

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * @author caojiantao-ext 用窗體展現國際象棋的棋盤
 */
public class _06 {

    public static void main(String[] args) {
        JFrame frame = new JFrame("國際象棋");
        frame.setSize(415, 435);
        // 假設棋盤為20*20
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                JLabel label = new JLabel();
                label.setSize(20, 20);
                label.setBackground(((i + j) % 2 == 0) ? Color.BLACK
                        : Color.white);
                label.setLocation(20 * i, 20 * j);
                // 設定不透明,要不然不會顯示
                label.setOpaque(true);
                frame.add(label);
            }
        }
        // 窗體居中顯示
        frame.setLocationRelativeTo(null);
        // 當視窗關閉程式結束
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 展示棋盤
        frame.setVisible(true);
    }
}

7.輸出字串排序(去掉重複項)

這裡寫圖片描述

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class PermutationTest{

    private static Set<String> set = new HashSet<String>();

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        char[] chars = scanner.next().toCharArray();
        permutation(chars, 0);
        System.out.print(set);
    }

    /**
     * 陣列元素交換,地址引用傳遞
     */
    static void swap(char[] arr, int idx1, int idx2) {
        char temp = arr[idx1];
        arr[idx1] = arr[idx2];
        arr[idx2] = temp;
    }

    /**
     * 遞迴排序
     */
    static void permutation(char[] chars, int index) {
        // 遞迴出口
        if (index == chars.length) {
            // 新增到set中,避免重複排序
            set.add(new String(chars));
        } else {
            for (int i = index; i < chars.length; i++) {
                // 交換陣列元素
                swap(chars, i, index);
                // 索引向後移一位,遞迴開始
                permutation(chars, index + 1);
                // 在每一次遞迴完成的時候記得還原陣列元素,保證最外層迴圈的資料來源不變
                swap(chars, i, index);
            }
        }
    }
}