2015年12月28日 星期一

Chapter 10 -- Model 進階項目

The Model as a Macro-Pattern
在MVC架構中,Model 元件內嵌了許多的功能,其負責的功能如下:
  • 展現一個介面給 Controller
  • 執行商業邏輯
  • 展現一個 JavaBean 合適的資料觀點給 View 元件!對 View 元件而言,是個方便使用的形式!
The View Helper Pattern
通常,OO(物件導向)原則之下,每個物件應該都是被設計成最好的狀態!但是,實情上卻不儘然如此,一定會有修改的時候!使用OO設計出來的物件,理論上是可以達成最小化的修改!
所以,依據規則,在設計 Model 時,不應考慮到 View 的展現!而 View 的設計,應該使用 EL 語言,一種非程式化的語言!另外,在純 Model 程式轉換或其他流程的轉換,View 可以提展現的介面!不過,必須注意 EL 並非是最佳的解決方案!
在設計專案過程中,每個 Model 本身的設計,可以忽略 View !等到設計好 Model 時,再利用 View ,將 Model 串接起來!所以 View Helper 是方便的做法,設計一個合適的介面給 View,然後,可連結到幾個純 Model 物件!

Database and Resource Access
  • Data Access Object(DAO) 樣式

  • DAO 樣式的好處

    • 物件與商業邏輯可以分開!
    • 在改變系統時,DAO 樣式物件可提供程式可重複利用性與彈性!
    • 無論是 Servlet 或 JSP 的客戶端程式,均可重複利用相同的資料存取程式!
    • 前端程式不用改變任存已經存在的取存資料程式,即可改變 web 層次的元件!
    • 後端程式不用改變任何前端程式,即可加入不同的資料來源!
  • JDBC API

    • JDBC API 是 Java 用來連結關連式資料庫的技術
    • 開發連結資料庫程式時,重點是:如何管理從 Web 到資料庫的通訊!

2015年12月25日 星期五

Tomcat 8 安裝

  • 在 Windows 7 上安裝
    • 下載 Tomcat 8 套件!官方網址:tomcat.apache.org
      ※PS:本次使用 64-bit Windows zip 版本
    • 放至適當目錄,並且解壓縮!
    • 至解壓縮目錄內,找到 conf tomcat-users.xml 檔案,並在檔案內,加入如下的程式內容:
      <role rolename="manager-gui"/>
      <role rolename="admin-gui"/>
      <user username="admin" password="a123456" roles="manager-gui,admin-gui"/>
      <!--以下這行不是新增上去的! -->
      </tomcat-users>
      

    • 至解壓縮目錄內,找到 bin startup.bat 檔案,並在檔案內,加入如下的程式內容:
      rem 以下這行不是自行加上去的:
      setlocal
      
      rem 以下這行才是自己加上去的:
      set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_51"
      
      
    • 另外,再找一下 bin stutdown.bat 檔案,內容設定與上一個檔案相同!
    • 利用「命令提示字元」視窗,執行 startup.bat 檔案!
    • 打開瀏覽器,輸入 http://localhost:8080 ,查看結果!


  • CentOS 7 上安裝 
    • 
      



  • 2015年10月12日 星期一

    Java 的 Thread 基本應用

    繼承 Thread :
    public class ExampleThread extends Thread{
        @Override
        public void run() {
            for(int i = 0; i<100; i++){
                System.out.println("i: " + i);
            }
        }
    }
    

    public class Demo {
        public static void main(String[] args){
            ExampleThread t1 = new ExampleThread();
            t1.start();
        }
    }
    

    執行 Runnable 介面 :
    public class ExampleRunnable implements Runnable{
    
        @Override
        public void run() {
            for(int i = 0; i<100; i++){
                System.out.println("i: " + i);
            }
        }  
    }
    

    public class RunnableDemo {
         public static void main(String[] args){
            ExampleRunnable r1 = new ExampleRunnable();
            Thread t1 = new Thread(r1);
            t1.start();
        }
    }
    

    Java 檔案管理程式

    NIO.2 基本應用:
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    public class NIODemo {
        public static void main(String[] args){
            Path p1 = Paths.get("C:\\workspace\\test\\test1\\hello.text");
            System.out.println("Get File Name: " + p1.getFileName());
            System.out.println("Get Parent: " + p1.getParent());
            System.out.println("Get Name Count: " + p1.getNameCount());
            System.out.println("Get Root:" + p1.getRoot());
            System.out.println("Is Absolute:" + p1.isAbsolute());
            System.out.println("To Absolute Path:" + p1.toAbsolutePath());
            System.out.println("To URI Path:" + p1.toUri());
        }
    }
    

    Serializable 的應用

    範例:
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.Serializable;
    
    public class Stock implements Serializable{
        private static final long serialVersionUID = 100L;
        private String symbol;
        private int shares;
        private double purchasePrice;
        private transient double currPrice;
    
        public Stock(String symbol, int shares, double purchasePrice) {
            this.symbol = symbol;
            this.shares = shares;
            this.purchasePrice = purchasePrice;
            setStockPrice();
        }
        
        private void setStockPrice() {
            this.currPrice = this.purchasePrice;
        }
         
        private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException{
            ois.defaultReadObject();
            setStockPrice();
        }
    }
    

    import java.io.FileInputStream;
    import java.io.Serializable;
    import java.util.Set;
    
    public class Portfolio implements Serializable{
        public transient FileInputStream inputFile;
        public static int BASE = 100;
        private transient int totalValue = 10;
        private Set stocks;
     
        Portfolio(Stock s1, Stock s2, Stock s3) {
            this.stocks.add(s1);
            this.stocks.add(s2);
            this.stocks.add(s3);
        }  
    }
    

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class Demo {
        public static void main(String[] args){
        
            Stock s1 = new Stock("ORCL",100, 32.5);
            Stock s2 = new Stock("AOOL",100, 245);
            Stock s3 = new Stock("GOGL",100, 54.67);
            
            Portfolio p = new Portfolio(s1,s2,s3);
            
            try(FileOutputStream fos = new FileOutputStream(args[0]);
                ObjectOutputStream out = new ObjectOutputStream(fos)){
                out.writeObject(p);
            } catch (IOException ex) {
               System.out.println("Exception writing out Portfolio :" + ex);
            }
            
            try(FileInputStream fis = new FileInputStream(args[0]);
                ObjectInputStream in = new ObjectInputStream(fis)){
                Portfolio newP = (Portfolio)in.readObject();
            } catch (ClassNotFoundException | IOException ex) {
               System.out.println("Exception reading in Portfolio :" + ex);
            }
        }
    }
    

    2015年10月7日 星期三

    I/O Chain 的練習

    Buffer 與 File 的 Chain :
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class ChainDemo {
        public static void main(String[] args){
            try(BufferedReader bufInput = new BufferedReader(new FileReader(args[0]));
                BufferedWriter bufOutput = new BufferedWriter(new FileWriter(args[1]))){
                String line = "";
                while ((line = bufInput.readLine()) != null){
                    bufOutput.write(line);
                    bufOutput.newLine();
                }
            }   catch (FileNotFoundException ex) {
                System.out.println("File not found!");
            } catch (IOException ex) {
                System.out.println("I/O Error");
            }  
        }
    }
    

    InputStream 與 OutputStream

    Byte 種類的 I/O 處理:
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class StreamDemo {
        public static void main(String[] args){
            byte[] data = new byte[128];
            int dataLen = data.length;
            
            try(FileInputStream fis = new FileInputStream(args[0]);
                FileOutputStream fos = new FileOutputStream(args[1])){
                System.out.println("Bytes available: " + fis.available());
                int count = 0;
                int read = 0;
                while ((read = fis.read(data)) != -1){
                    if (read < dataLen) 
                        fos.write(data,0,read);
                    else
                        fos.write(data);
                    count += read;
                }
                System.out.println("Wrote: " + count);
            }   catch (FileNotFoundException ex) {
                System.out.println("File not Found! " + ex);
            } catch (IOException ex) {
                System.out.println("I/O Error! " + ex);
            }
        }
    }
    

    Assertion 用法


    import java.util.Scanner;
    
    public class Demo {
        public static void main(String[] args){
        
            Scanner scanner = new Scanner(System.in);
            System.out.print("Please input positive number:");
            int input = scanner.nextInt();
            if (input > 0){
                System.out.println("Number: " + input);
            } else {
                assert (input > 0): "執行有誤....";
                System.out.println("Error : " + input);
            }
        }
    }
    

    Java 例外處理--AutoCloseable

    有 catch 敘述:
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class OpenFileDemo{
      public static void main(String[] args){
        System.out.println("About to open a file...");
        
        try (InputStream in = new FileInputStream("hello.txt")){
          System.out.println("File is opened..");
          int data = in.read();
        } catch (FileNotFoundException e){
            System.out.println(e.getMessage());
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
      }
    }
    

    沒有 catch 敘述(利用 throws,丟給上頭去傷腦筋...)
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class ThrowDemo {
        public static void main(String[] args){
            try {    
                int data = readByteFromFile();
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    
        private static int readByteFromFile() throws FileNotFoundException, IOException {
            try(InputStream in = new FileInputStream("a.txt")){
                System.out.println("File is opening...");
                return in.read();
            }
        }
    }
    

    2015年10月2日 星期五

    正規化表示式

    Pattern & Matcher 的應用:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegxDemo {
        public static void main(String[] args){
        
            String test = "He was a teacher";
            
            Pattern p1 = Pattern.compile("w.s");
            Matcher m1 = p1.matcher(test);
            if (m1.find()){
                System.out.println("Found: " + m1.group());
            }
            
            Pattern p2 = Pattern.compile("w[abc]s");
            Matcher m2 = p2.matcher(test);
            if (m2.find()){
                System.out.println("Found: " + m2.group());
            }
            
            Pattern p3 = Pattern.compile("t[^xyz]acher");
            Matcher m3 = p3.matcher(test);
            if (m3.find()){
                System.out.println("Found: " + m3.group());
            }
    
            String header = "<h1>Hello World<h1>";
            Pattern p4 = Pattern.compile("h1");
            Matcher m4 = p4.matcher(header);
            if (m4.find()){
                System.out.println("Found: " + m4.group());
                header = m4.replaceAll("p");
                System.out.println(header);
            }  
    
        }
    }
    

    Scanner 切割字串的應用


    import java.util.Scanner;
    
    public class ScannerDemo {
        public static void main(String[] args){
            StringBuilder sb = new StringBuilder(64);
            String test = "1.1, 2.2, 3.3";
            float fsum = 0.0f;
            
            Scanner s = new Scanner(test).useDelimiter(", ");
            while(s.hasNextFloat()){
                float f = s.nextFloat();
                fsum += f;
                sb.append(f).append(" ");
            }
            System.out.println("Values for: " + sb.toString());
            System.out.println("FSum: " + fsum);
        }
    }
    

    StringBuilder 用法


    import java.io.PrintWriter;
    import java.util.StringTokenizer;
    
    public class StringDemo {
        public static void main(String[] args){
            
            //StringBuilder 範例
            StringBuilder sb = new StringBuilder(500);
            
            sb.append(", this is a good day!");
            sb.insert(0,"Today is Friday!");
            for (int i = 1; i< 11 ; i++){
                sb.append(i).append("    ");
            }
            sb.append("] times");
            System.out.println(sb.toString());
            System.out.println();
            
            //String Methods 範例
            PrintWriter pw = new PrintWriter(System.out, true);
            String tc01 = "It was the best of times";
            String tc02 = "It was the worst of times";
            
            if (tc01.equals(tc02)){
                pw.println("Strings match...");
            }
            if (tc01.contains("It was")){
                pw.println("It was found");
            }
            String temp = tc02.replace("w", "zw");
            pw.println(temp);
            pw.println(tc02.substring(5, 12));
             pw.println();
             
            //String Split 範例
            String shirts = "Blue Shirt, Red Shirt, Black Shirt, Maroon Shirt";
            
            String[] results = shirts.split(", ");
            for (String shirtStr:results){
                pw.println(shirtStr);
            }
             pw.println();
             
            //Tokenizer 範例
            StringTokenizer st = new StringTokenizer(shirts, ", ");
            while(st.hasMoreTokens()){
                pw.println(st.nextToken());
            }
        }
    }
    
    

    Properties 的使用


    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Properties;
    
    public class Demo1 {
        public static void main(String[] args) throws FileNotFoundException{
        
            Properties myProps = new Properties();
            try{
                FileInputStream fis = new FileInputStream("C:\\ServerInfo.properties");
                myProps.load(fis);
            } catch (IOException e){
                System.out.println("Error: " + e.getMessage());
            }
            
            System.out.println("Server: " + myProps.getProperty("hostName"));
            System.out.println("User: " + myProps.getProperty("userName"));
            System.out.println("Password: " + myProps.getProperty("password"));
               
        }
    }
    

    Properties 的檔案內容:
    hostName=www.example.com
    userName=user
    password=pass
    

    2015年9月30日 星期三

    Comparator 的用法

    Comparator 的用法:
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class ComparatorDemo {
        public static void main(String[] args){
        
            List<Student> studentList = new ArrayList<>(3);
            Comparator<Student> sortName = new StudentSortName();
            Comparator<Student> sortGpa = new StudentSortGpa();
            
            studentList.add(new Student("Thomas Jefferson", 1111, 3.8));
            studentList.add(new Student("John Adams", 2222, 3.9));
            studentList.add(new Student("George Washington", 3333, 3.4));
            
            Collections.sort(studentList, sortName);
            for (Student student : studentList){
                System.out.println(student.getName());
            }
             Collections.sort(studentList, sortGpa);
            for (Student student : studentList){
                System.out.println(student.getGpa());
            }
        }
    }
    

    public class Student {
    private String name;
        private long id = 0;
        private double gpa = 0;
                
        public Student(String name, long id, double gpa) {
            this.name = name;
            this.id = id;
            this.gpa = gpa;
        }
    
        public String getName() {
            return name;
        }
    
        public double getGpa() {
            return gpa;
        }
    }
    

    import java.util.Comparator;
    
    public class StudentSortName implements Comparator<Student> {
    
        public StudentSortName() {
        }
    
        @Override
        public int compare(Student o1, Student o2) {
            int result = o1.getName().compareTo(o2.getName());
            if (result != 0){return result;}
            else { return 0;}
        }
    }
    

    import java.util.Comparator;
    
    public class StudentSortGpa implements Comparator<Student> {
    
        public StudentSortGpa() {
        }
    
        @Override
        public int compare(Student o1, Student o2) {
            if (o1.getGpa() < o2.getGpa()){return 1;}
            else if (o1.getGpa() > o2.getGpa()){ return -1;}
            else {return 0;}
        }
    }
    

    Comparable 的用法

    Comparable 的用法:
    public class ComparableStudent implements Comparable<ComparableStudent>{
        private String name;
        private long id = 0;
        private double gpa = 0.0;
    
        public ComparableStudent(String name, long id, double gpa) {
            this.name = name;
            this.id = id;
            this.gpa = gpa;
        }
    
        public String getName() {
            return name;
        }
            
        @Override
        public int compareTo(ComparableStudent o) {
            int result = this.name.compareTo(o.getName());
            if (result > 0){return 1;}
            else if (result < 0){return -1;}
            else {return 0;}
        }
    }
    

    Demo 程式:
    import java.util.Set;
    import java.util.TreeSet;
    
    public class Demo {
        public static void main(String[] args){
            Set<ComparableStudent> studentList = new TreeSet<>();
            
            studentList.add(new ComparableStudent("Thomas Jefferson", 1111, 3.8));
            studentList.add(new ComparableStudent("John Adams", 2222, 3.9));
            studentList.add(new ComparableStudent("George Washington", 3333, 3.4));
             
             for (ComparableStudent student : studentList){
                 System.out.println(student.getName());
             }
        }
    }
    

    Queue 的應用


    import java.util.ArrayDeque;
    import java.util.Deque;
    
    public class NewClass {
        public static void main(String[] args){
        
            Deque<String> stack = new ArrayDeque<>();
            stack.push("One");
            stack.push("Two");
            stack.push("Three");
            
            int size = stack.size() -1;
            while(size >= 0){
                System.out.println(stack.pop());
            }
        }
    }
    

    Map 應用


    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;
    
    public class MapDemo {
        public static void main(String[] args){
        
            Map<String, String> shirtList = new TreeMap<>();
            shirtList.put("S001", "Blue Shirt");
            shirtList.put("S002", "Black Shirt");
            shirtList.put("S003", "Gray Shirt");
            
            Set<String> keys = shirtList.keySet();
            System.out.println("====== Shirt List ======");
            for (String key : keys){
                System.out.println("Part#: " + key + " " 
                                   + shirtList.get(key));
            } 
        }
    }
    

    Set 應用

    某家公司的面試題目:
    import java.util.Set;
    import java.util.TreeSet;
    import java.util.Scanner;
    
    public class SetDemo {
        public static void main(String[] args){
        
            Set<Integer> num = new TreeSet<>();
            Scanner scanner = new Scanner(System.in);
            Integer[] b = new Integer[3];
            for (int i = 0; i < 3 ;  i++){
                System.out.print("Please the eage's length: ");
                num.add(scanner.nextInt());
            }
            num.toArray(b);
            if (b[2] < (b[0]+b[1])){
            switch (num.size()){
                case 1: 
                    System.out.println("正三角形");
                    break;
                case 2:
                    System.out.println("等腰三角形");
                    break;
                case 3:
                    if (triangle(b)){
                        System.out.println("直角三角形");
                    } else {
                        System.out.println("其他種類三角形");
                    }
            }
            } else {
                 System.out.println("無法構成三角形");
            }
        }
    
        private static boolean triangle(Integer[] b) {
            if ((b[2] * b[2]) == (b[0]*b[0] + b[1]*b[1])){
              return true;
            } else {
                return false;
            }
        }
    }
    
    
    

    2015年9月23日 星期三

    Boxing & UnBoxing

    AutoBoxing 與 Auto Unboxing:
    public class AutoBox {
        public static void main(String[] args){
        
            Integer intObject = new Integer(1);
            int intPrimitive = 2;
            
            Integer tempInteger;
            int tempPrimitive;
            
            tempInteger = new Integer(intPrimitive);
            tempPrimitive = intObject.intValue();
            
            tempInteger = intPrimitive;  //Auto Boxing
            tempPrimitive = intObject; // Auto Unboxing
        }
    }
    

    收集器:ArrayList & List

    Collection 利用 Generic 來實作的好處:
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class ArrayListDemo {
        public static void main(String[] args){
        
            List partList = new ArrayList<>();
            partList.add(new Integer(1111));
            partList.add(new Integer(2222));
            partList.add(new Integer(3333));
            partList.add("Hello World");  //Compile Error : Not Integer
            
            // 利用 Iterator 來遍訪 ArrayList 內的 elements 
            Iterator elements = partList.iterator();  
            while (elements.hasNext()){
                Integer partNumberObject = elements.next();
                int partNumber = partNumberObject.intValue();
                
                System.out.println("Part Number: " + partNumber);
            }
        }
    }
    

    Java 泛型概念

    泛型的功能:
    public class Shirt {
       private int shirtID = 0;
    
        public int getShirtID() {
            return shirtID;
        }
    
        public void setShirtID(int shirtID) {
            this.shirtID = shirtID;
        } 
    }
    

    public class CacheAny {
        private T t;
        public void add(T t){
            this.t = t;
        }
        public T get(){
            return this.t;
        }
    }
    

    public class Demo {
        public static void main(String[] args){
            CacheAny myMessages = new CacheAny<>();
            myMessages.add("This is my Shirt!");
            System.out.println(myMessages.get().toString());
            
            CacheAny myShirt = new CacheAny<>();
            myShirt.add(new Shirt());
            myShirt.get().setShirtID(123456);
            System.out.println("Shirt ID :" + myShirt.get().getShirtID());
        }
    }
    

    Composition Implementation

    Composition 實作範例:
    public interface Car {
        public void start();
    }
    

    public abstract class BasicCar {
        public abstract void start();
    }
    

    public class Diesel extends BasicCar{
        public void start(){
            System.out.println("Diesel Start....");
        }
    }
    

    public class Mobile extends BasicCar{
        public void ignite(){
            System.out.println("Power turn on ...");
        }
    
        @Override
        public void start() {
            this.ignite();
        }
    }
    

    public class Hybrid  implements Car{
        private Diesel die = new Diesel();
        private Mobile m1 = new Mobile();
        
        public void start(){
            die.start();
            m1.ignite();
        }   
    }
    

    public class Racing extends Hybrid{
        public void start(){
            super.start();
            System.out.println("Engine is starting.....");
        }
    }
    

    public class Demo {
        public static void main(String[] args){
        
            Racing r1 = new Racing();
            r1.start();
        }
    }
    

    2015年9月21日 星期一

    Java 介面的繼承


    public interface Boats {
        public void launch();
    }
    

    public interface MotorizedBoat extends Boats{
        public void start();
    }
    

    public interface Car {
        public void start();
    }
    

    public class BasicCar implements Car{
    
        @Override
        public void start() {
            Engine e1 = new Engine(){
                public String start(){
                    return ("Engine is :" + start());
                }
            };
        }
    
        private static class Engine {
            public String start(){
                return "Starting ....";
            }
        }  
    }
    

    public class AmphibiousCar extends BasicCar implements MotorizedBoat , java.io.Serializable{
    
        @Override
        public void launch() {
            System.out.println("要行駛了....");
        }   
    }
    

    Java 介面的用法

    最簡單的介面宣告:
    public interface EletronicDevice {
        public void turnOn();
        public void turnOff();
    }
    

    使用方式:
    public class Television implements EletronicDevice{
    
        @Override
        public void turnOn() {
            System.out.println("電視機開啟中...");
            initializeScreen();
        }
    
        @Override
        public void turnOff() {
            initializeScreen();
            System.out.println("電視機關閉中...");
        }
        
        public void changeChannel(int channel){
            System.out.printf("切換至第 %d 台", channel);
        }
        
        private void initializeScreen(){
            System.out.println("清除螢幕視窗....");
        }
    }
    

    執行方式:
    public class Demo {
        public static void main(String[] args){
            
            EletronicDevice ed = new Television();
            ed.turnOn();
    
            //介面與類別相同的功能:casting
            ((Television)ed).changeChannel(2); 
    
            ed.turnOff();
            String s = ed.toString();
            System.out.println(s);
        }
    }
    

    巢狀式類別

    內部類別示範:
    public class Car {
    
        private boolean running = false;
        private Engine engine = new Engine();
    
        private class Engine {
            public void start(){
                running = true;
                System.out.println("引擎起動中....");
            }
        }
        
        public void start(){
            engine.start();
            System.out.println("汽車狀態: 準備行駛.....");
        }
    }
    

    public class Demo {
        public static void main(String[] args){
            Car c1 = new Car();
            c1.start();
        
        }
    }
    

    暱名內部類別示範:
    public class CarBrand {
    
        //建立一個內部有暱名類別的物件
        public LandRover l1 = new LandRover(){
    
            @Override
            public String toString() {
                return ("Land Rover : " + l1.getBrand1());
            }    
        }; //注意節尾的結束符號
                
        // 這是一般的內部類別用法
        private class LandRover {
            private String brand1 = "Defender !";
            public String getBrand1(){
                return brand1;
            }
        }
    }
    

    public class Demo {
        public static void main(String[] args){
            CarBrand c1 = new CarBrand();
            System.out.println(c1.l1);
        }
    }
    

    Singleton Design Pattern 的範例

    Singleton Design Pattern 的類別,只能實例化一次:
    public class Husband {
    
      private static final Husband yourlover = new Husband();
      private static String name = "Peter" ;
      
      private Husband(){}
    
      public static Husband getYourLover(){
          System.out.println("Your Husband: " + name);
        return yourlover;
      }
    } 
    

    public class Demo {
        public static void main(String[] args){
            Husband.getYourLover();
        }
    }
    
    

    2015年9月19日 星期六

    利用 Eclipse 來寫 Java EE 程式


    1. http://pclevin.blogspot.tw/2014/08/javaservlet-hello-world-example.html

    2. http://www.dotblogs.com.tw/alantsai/archive/2013/09/28/servlet-helloworld.aspx

    3. http://xml-nchu.blogspot.tw/2012/10/java-servlet.html

    良葛格寫的 Java EE


    1. http://www.codedata.com.tw/java/java-tutorial-the-3rd-class-3-servlet-jsp/

    2. http://openhome.cc/Gossip/ServletJSP/

    3. http://www.slideshare.net/JustinSDK/servlet-jsp-1-web

    打包成 war 的方式

    1. http://shuyangyang.blog.51cto.com/1685768/1125131

    掌握 Java EE 技術


    1. http://liumh.blog.51cto.com/1388196/504019

    2015年9月18日 星期五

    Enum 使用方式

    Java 的 Enum:
    public enum PowerState {
       OFF("This System is off"),
        ON("This System is on"),
        SUSPEND("This System is Suspend");
        
        private String description;
        
        private PowerState(String d){
            description = d;
        }
        public String getDescription(){
            return this.description;
        }
    }
    

    測試一下:
    public class Computer {
    
        void setState(PowerState powerState) {
        
            switch(powerState){
                case OFF:
                    System.out.println(powerState.getDescription());
                    break;
                case ON:
                    System.out.println(powerState.getDescription());
                    break;
                case SUSPEND:
                    System.out.println(powerState.getDescription());
                    break;
            }
        }  
    }
    

    public class Demo {
        public static void main(String[] args){
        
            Computer comp = new Computer();
        
            comp.setState(PowerState.OFF);
            
        }
    }
    

    物件的比較


    物件的比較,原則上必須 Override Object 物件內的 equals() 方法:
    public class Employee {
        
        private int empId;
        private String name;
        private String ssn;
        private double salary;
    
        public Employee(int empId, String name, String ssn, double salary) {
            this.empId = empId;
            this.name = name;
            this.ssn = ssn;
            this.salary = salary;
        }
    
        @Override
        public boolean equals(Object obj) {
            boolean result = false;
            
            if ((obj != null) && (obj instanceof Employee)){
                Employee e = (Employee)obj;
                if ((e.empId == this.empId) &&
                        (e.name.equals(this.name)) &&
                        (e.ssn.equals(this.ssn)) &&
                        (e.salary == this.salary)){
                        result = true;
                }
            }
            
            return result; 
        }
    
       //......請參考這一篇程式內容......
    
    }
    

    測試用程式:
    public class Demo {
        public static void main(String[] args){
               
            Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
            Employee m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
            Employee es = e;
            Employee es2 = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
            
            if ( e ==  es ){
                System.out.println("1.同一物件");
            }
            
            if ( e.equals(es)){
                System.out.println("1.物件內容相同");
            }
            
            if ( e ==  es2 ){
                System.out.println("2.同一物件");
            }
            
            if ( e.equals(es2)){
                System.out.println("2.物件內容相同");
            }
            
            if ( e ==  m ){
                System.out.println("3.同一物件");
            }
            
            if ( e.equals(m)){
                System.out.println("3.物件內容相同");
            }
        }
    }
    

    2015年9月16日 星期三

    Polymorphism 用法

    Polymorphism (多型)用法:
    public class Employee {
    
        //....參考這一篇內容.....
         protected int calculateStock() {
            return 10;
        }
    }
    

    public class Manager extends Employee{
    
        //....參考這一篇內容.....
        public int calculateStock() {
            return 20;
        }
    }
    

    新的類別:
    public class EmployeeStackPlan {
    
        private float stockMultiplier = 1.5f;
    
        // 使用父類別當引數:
        public int grantStock (Employee e){
            return (int)(stockMultiplier * e.calculateStock());
        }
    }
    

    執行的執行:
    public class Demo {
        public static void main(String[] args){
        
        Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);    
        Manager m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
        Employee em = new Manager(103, "Williams Tim", "014-87-5679",123_560.54, "Production");
    
        System.out.println("Stock: " + e.calculateStock());
        System.out.println("Stock: " + m.calculateStock());
        System.out.println("Stock: " + em.calculateStock());
        
    

    Override 用法

    Java 的Override 用法:
    public class Employee {
        
        private int empId;
        private String name;
        private String ssn;
        private double salary;
    
        public Employee(int empId, String name, String ssn, double salary) {
            this.empId = empId;
            this.name = name;
            this.ssn = ssn;
            this.salary = salary;
        }
    
        public String getDetail(){
            return ("Employee ID : " + getEmpId() +
                    " Employee Name: " + getName());
        }
    
        //......一堆 getter & setter ......
    }
    

    public class Manager extends Employee{
        
        private String deptName;
    
        public Manager(int empId, String name, String ssn, double salary, String deptName) {
            super(empId, name, ssn, salary);
            this.deptName = deptName;
        }
        public String getDetail(){
            return (super.getDetail() + 
                    " Department: " + getDeptName());
        }
     //......一堆 getter & setter ......
    }
    

    public class Demo {
        public static void main(String[] args){
        
            Employee e = new Employee(101, "Jim Smith", "011-12-2345", 100_000.00);
            Manager m = new Manager(102, "Joan Kern", "012-23-4567",110_450.54, "Marketing");
            System.out.println(e.getDetail());
            System.out.println(m.getDetail());
        }
    }
    

    Java 權限修飾詞

    Java 權限修飾詞: private、default、protected、public
    package demo;
    
    public class Foo {
        private int result = 20;
        protected int getResult(){
            return result;
        }
    }
    

    package test;
    
    import demo.Foo;
    
    public class Bar extends Foo{
        private int sum = 10;
        public void reportSum(){
            sum += getResult();
            System.out.println("Sum :" + sum );
        }
    }
    

    public class Demo {
        public static void main(String[] args){
        
            Bar abc = new Bar();
            abc.reportSum();
        } 
    }
    

    Method 的可變長度引數

    方法中,可變長度的引數宣告:
    public class Statistics {
        public float average(int... nums){
        
            int sum = 0;
            for (int x : nums){
                sum += x;
            }
            return ((float)sum / nums.length);
        }
    }
    

    使用方式:
    public class Demo {
        public static void main(String[] args){
        
            Statistics abc = new Statistics();
            int[] nums = {32,67,98,34,76};
            System.out.println("Average: " + abc.average(nums));
        }
    }
    

    2015年9月14日 星期一

    物件與多型

    Java 多型 (Polymorphism) 的使用:
    範例:Employee
    public class Employee {
        
        private int empId;
        private String name;
        private String ssn;
        private double salary;
    
        public Employee() {
        }
    
        public Employee(int empId, String name, String ssn, double salary) {
            this.empId = empId;
            this.name = name;
            this.ssn = ssn;
            this.salary = salary;
        }
    
        //......一堆 getter 與 setter ......
    
       public void raiseSalary(double increase){
            salary += increase;
        }
    
    }
    

    Manager 繼承 Employee :
    public class Manager extends Employee{
        
        private String deptName;
    
        public Manager() {
        }
    
        public Manager(int empId, String name, String ssn, double salary, String deptName) {
            //super();
            super(empId, name, ssn, salary);
            this.deptName = deptName;
        }
    
        public String getDeptName() {
            return deptName;
        }
    
        public void setDeptName(String deptName) {
            this.deptName = deptName;
        }   
    }
    

    最後來個大Demo :
    public class Demo {
        public static void main(String[] args){
        
            Manager mgr = new Manager(102, "Barbara Jones", "107-99-9078", 109345.67, "Marketing");
            mgr.raiseSalary(10000.00);
            String dept = mgr.getDeptName();
            
            Employee emp = new Manager();
            //錯誤
            //emp.setDeptName("Marketing");
            ((Manager)emp).setDeptName("Marketing");
        }
    }
    

    傳值呼叫

    Java 傳值方式:Call by Value
    針對基本數值:
    int x = 3;
    int y = x;
    // x 將數值直接 copy 給 y
    

    針對物件:
    public class Demo {
        public static void main(String[] args){
        
            Employee x = new Employee();
            System.out.println("Salary: " + x.salary);
            foo(x);
            System.out.println("New Salary: " + x.salary);
        }
    
        // x -> e ,直接 copy 記憶體位址值
        public static void foo(Employee e) {
            //e = new Employee();
            e.setSalary(5000.00);
        }
    }
    
    class Employee {
        double salary = 1000.00;
    
        void setSalary(double d) {
            this.salary = d;
        }  
    }
    

    2015年9月11日 星期五

    Package & Import 用法

    利用 Package 來將專案內的檔案,進行分類:
    package com.HR;
    
    public class Employee {
    
        private String name;
        private int empID;
        private String ssn;
        private double salary;
    
        public Employee() {
        }
    
        public Employee(int empID, double salary, String ssn, String name) {
            this.empID = empID;
            this.salary = salary;
            this.ssn = ssn;
            this.name = name;
        }
    
        public double getSalary() {
            return salary;
        }
    
        public String getSsn() {
            return ssn;
        }
    
        public String getName() {
            return name;
        }
    
        public int getEmpID() {
            return empID;
        }
    
        public void setSalary(double salary) {
            this.salary = salary;
        }
    
        public void setSsn(String ssn) {
            this.ssn = ssn;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setEmpID(int empID) {
            this.empID = empID;
        }
    }
    

    Import 進來上述的 Class :
    import com.HR.Employee;
    
    public class Demo {
        public static void main(String[] args){
        
            Employee e1 = new Employee();
        
        }
    }
    

    Java 的 String 物件

    String 是常見的 Java 字串物件:
    public class StringOperations {
        
        public static void main(String[] args) {
           
            String string2 = "World";
            String string3 = "";
            
            string3 = "Hello".concat(string2);
            System.out.println("String3: " + string3);
            
            System.out.println("Length: " + string3.length());
            
            System.out.println("Sub: " + string3.substring(0, 5));
            
            System.out.println("Upper: " + string3.toUpperCase());
        }
    }
    

    Java 介面實作與應用

    Java 介面宣告方式:
    public interface Refuel{
      
        //介面的方法,可視為抽象方法!
        public String doRefuel();
    }
    

    修改一下原來的 Sedan 類別
    public class Sedan extends Vehicle implements Refuel{
    
        private char audioClass;
        private double fuelTank;
    
        Sedan(int wheels, String engineType, double weight, char audio , double fuelTank){
          super(wheels,engineType,weight);
          this.audioClass = audio;
          this.fuelTank = fuelTank;
        }
    
        //實作抽象方法
         public void ignite(){
           System.out.println("Engine start!");
        }
    
        //實作介面方的方法
        public String doRefuel(){
          this.fuelTank = 20.00;
          return "Refeuel :" + this.fuelTank;
        }
    }
    

    實作 Sedan 類別:
    public class Demo {
     public static void main(String[] args){
    
        Sedan bm = new Sedan(4, "Diesel" , 2231.21 , 'A' , 0.0);
        System.out.println(bm.doRefuel());
        bm.ignite();
     }
    }
    

    Java 抽象類別

    Java 抽象類別的使用:(hint: 把所有類別重複的東西,描象化成一個 super 類別!)
    public abstract class Vehicle{
      
       private int wheels;
       private String engineType;
       private double weight;
    
       Vehicle(int wheels, String engineType, double weight){
           setWheels(wheels);
           setEngineType(engineType);
           setWeight(weight);
       }
    
       public abstract void ignite(); //這是抽象方法
    
       public int getWheels(){
         return this.wheels;
       }
    
       public String getEngineType(){
         return this.engineType;
       }
    
       public double getWeight(){
         return this.weight;
       }
    
       public void setWheels(int wheels){
         this.wheels = wheels;
       }
    
       public void setEngineType(String engineType){
         this.engineType = engineType;
       }
    
       public void setWeight(double weight){
         this.weight = weight;
       }
    }
    

    利用繼承,才能使用抽象類別:
    public class Sedan extends Vehicle{
    
        private char audioClass;
    
        Sedan(int wheels, String engineType, double weight, char audio){
          super(wheels,engineType,weight);
          this.audioClass = audio;
        }
    
        //實作抽象方法
         public void ignite(){
           System.out.println("Engine start!");
        }
    }
    

    實作時,不可以實例化抽象類別:
    public class Demo {
     public static void main(String[] args){
    
        //錯誤的範例:
        //Vehicle vo = new Vehicle(4, "Gas" , 1234.32);
    
        //正確的範例:
        Sedan bm = new Sedan(4, "Diesel" , 2231.21 , 'A');
        bm.ignite();
     }
    }
    

    2015年9月9日 星期三

    Java 例外處理

    Java 例外處理(基本處理方式):
    import java.util.Scanner;
    
    public class ErrorDemo{
    
     public static void main(String[] args){
     
      int input = 0;
      Scanner scanner = new Scanner(System.in);
      System.out.print("請輸入一個整數:");
      try{
       input = scanner.nextInt();
      } catch (Exception e){
       System.out.println("請輸入整數!");
      }
     }
    }
    

    使用 throws & throw :
    public class TestArray{
    
     int [] intArray;
        public TestArray(int size){
      intArray = new int[size];
     }
     
     public void addElement(int index, int value) throws RuntimeException{
      intArray[index] = value;
      throw new ArrayIndexOutOfBoundsException();
     }
    }
    

    public class ExceptionDemo{
    
     public static void main(String[] args){
     
      TestArray myTestArray = new TestArray(5);
      try {
       myTestArray.addElement(5, 23);
      } catch (RuntimeException e){
       System.out.println("超出陣列大小!");
      }
     }
    }
    

    Multi-Exception 的用法:
    import java.io.*;
    
    public class MultiExceptionDemo{
    
     public static void main(String[] args){
     
      try{
       createFile();
      } catch (IOException ex1){
       System.out.println(ex1);
      } catch (IllegalArgumentException ex2){
       System.out.println(ex2);
      } catch (Exception ex3){
       System.out.println(ex3);
      }
     }
     
     public static void createFile() throws IOException{
      File test = new File("C://workspace//test.txt");
      File temp1 = test.createTempFile("te123",null,test);
      System.out.println("Temp filename is " + temp1.getPath());
      int[] myInt = new int[5];
      myInt[5] = 25;
     }
    }
    

    好用的 Java Project idea


    外國老師提供給學生的 java project  idea !!

    http://mindprod.com/project/projects.html

    2015年9月2日 星期三

    Java 繼承方式

    利用繼承來減少程式碼:
    public class Clothing{
    
     private int shirtID = 0;
     private String description = "-----";
     private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
     private double price = 0.0;
     
     //constructors
     public Clothing(int shirtID, String description, char colorCode, double price){
      setShirtID(shirtID);
      setDescription(description);
      setColorCode(colorCode);
      setPrice(price);
     }
     public void setPrice(double price){
      this.price = price;
     }
     public double getPrice(){
      return this.price;
     }
     public void setDescription(String content){
      this.description = content;
     }
     public String getDescription(){
      return this.description;
     }
     public void setShirtID(int shirtID){
      this.shirtID = shirtID;
     }
     public int getShirtID(){
      return this.shirtID;
     }
     public char getColorCode(){
      return colorCode;
     }
     public void setColorCode(char newChar){
      switch(newChar){
       case 'R':
       case 'G':
       case 'B':
       case 'W':
       this.colorCode = newChar;
       break;
       default:
       System.out.println("This ColorCode is wrong!");
      } 
     }
     
     //顯示 Shirt 相關資料
     public void display(){
     
      System.out.println("Cloth ID: " +  shirtID);
      System.out.println("Description: " + description);
      System.out.println("Cloth Color: " + colorCode);
      System.out.println("Cloth's price: " + price);
     }
    }
    

    Shirt 繼承 Clothing 的方式:
    
    public class Shirt extends Clothing{
    
     private char fit = 'U'; //'S','M','L'
     
     //constructors
     public Shirt(int shirtID, String description, char colorCode,
                  double price, char fit){
      super(shirtID,description,colorCode,price);
      setFit(fit);
     }
     public char getFit(){
      return fit;
     }
     public void setFit(char newFit){
      switch(newFit){
       case 'S':
       case 'M':
       case 'L':
       this.fit = newFit;
       break;
       default:
       System.out.println("This Fit is wrong!");
      }
     }
     //Overriding Clothing display method
     public void display(){
      System.out.println("Shirt ID: " +  getShirtID());
      System.out.println("Description: " + getDescription());
      System.out.println("Shirt Color: " + getColorCode());
      System.out.println("Shirt's price: " + getPrice());
      System.out.println("Shirt Fit: " + getFit());
     }
    }
    

    執行方式:
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt(
          321,"NET new Shirt Style!",'B',121.22,'L');
      
      myShirt.display();
     }
    }
    

    Java 建構式

    Java 建構式與預設建構式:
    public class Shirt{
    
    ....omit................
    
    //constructors
     Shirt(){}
     
     Shirt(char colorCode){
      setColorCode(colorCode);
     }
     
     Shirt(int shirtID, char colorCode){
      this(colorCode);
      setShirtID(shirtID);
     }
    
    ....omit.........
    
    }
    

    執行建構式的方式:
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt('G');
         
      System.out.println("ColorCode: " + myShirt.getColorCode());
     
     }
    }
    

    Java 封裝的方法

    Encapsulation 的方式:
    public class Shirt{
    
     private int shirtID = 0;
     private String description = "-----";
     
     //public char colorCode = 'U';//Un-encapsulation
     
     private char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
     private double price = 0.0;
     
     public char getColorCode(){
      return colorCode;
     }
     
     public void setColorCode(char newChar){
      switch(newChar){
       case 'R':
       case 'G':
       case 'B':
       case 'W':
         this.colorCode = newChar;
         break;
       default:
       System.out.println("This ColorCode is wrong!");
      }  
     }
    
     //顯示 Shirt 相關資料
     public void displayInformation(){
     
      System.out.println("Shirt ID: " +  shirtID);
      System.out.println("Description: " + description);
      System.out.println("Shirt Color: " + colorCode);
      System.out.println("Shirt's price: " + price);
     }
    }
    

    執行該物件的方法:
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt();
      
      //myShirt.colorCode = 'B';
      myShirt.setColorCode('B');
        
      System.out.println("ColorCode: " + myShirt.getColorCode());
     
     }
    }
    

    2015年8月31日 星期一

    Static 的用法

    Java 中的 Static 用法:
    
    import java.util.Scanner;
    
    public class blenderDemo2{
     static int juice = 0;
     
     public static void makeJuice(int fruit){
      
      switch(fruit){
       case 1:
        juice += 150;
        break;
       case 2:
        juice += 300;
        break;
       case 3:
        juice += 400;
        break;
      }   
     }
    
     public static void main(String[] args){
     
      Scanner scanner = new Scanner(System.in);
      //blenderDemo2 myBlender = new blenderDemo2();
      
      System.out.print("請選擇水果種類:1) 蘋果  2) 香蕉 3) 芒果");
      int fruit = scanner.nextInt();
        
      switch(fruit){
       case 1:
        blenderDemo2.makeJuice(1);
        System.out.printf("蘋果汁:%d CC", blenderDemo2.juice);
        
       case 2:
        blenderDemo2.makeJuice(2);
        System.out.printf("香蕉牛奶:%d CC", blenderDemo2.juice);
        
       case 3:
        blenderDemo2.makeJuice(3);
        System.out.printf("芒果冰沙:%d CC", blenderDemo2.juice);
        
      }
     }
    }
    
    

    Overload 的語法

    Java 的 Overload 語法:
    
    import java.util.Scanner;
    
    public class blenderDemo{
    
     public static void main(String[] args){
     
      Scanner scanner = new Scanner(System.in);
      Blender myBlender = new Blender();
      
      System.out.print("請選擇水果種類:1) 蘋果  2) 香蕉 3) 芒果");
      int fruit = scanner.nextInt();
      
      switch(fruit){
       case 1:
        System.out.printf("蘋果汁:%d CC",myBlender.makeJuice(1));
        break;
       case 2:
        System.out.printf("香蕉牛奶:%d CC",myBlender.makeJuice(2,100));
        break;
       case 3:
        System.out.printf("芒果冰沙:%.2f CC",myBlender.makeJuice(3,100,200));
        break;
      } 
     }
    }
    

    public class Blender{
    
     public int makeJuice(int fruit){
      int juice = 0;
      switch(fruit){
       case 1:
        juice = 150;
        break;
       case 2:
        juice = 300;
        break;
       case 3:
        juice = 400;
        break;
      }   
      return juice;
     }
     
     public int makeJuice(int fruit, int milk){
      return (this.makeJuice(fruit)+ milk);
     }
     
     public double makeJuice(int fruit, int milk, int ice){
      return (this.makeJuice(fruit,milk)+ ice)/2.0;
     }
    }
    

    2015年8月29日 星期六

    Java 考試考古題

    http://www.wanlibo.com/mydoc-54137169-6.html&folderId=0

    http://ppp.show55.info:8090/se2-hpFj6/?redurl_ww.lzzpp.net

    http://www.itpub.net/forum.php

    http://www.cjsdn.net/post/page?bid=9&sty=0&tpg=2&age=0&s=-1

    http://wenku.it168.com/d_001448427.shtml

    http://218.14.151.180:82/wenku.it168.com/d_000575622.shtml

    Java 並行 API

    Java 的 java.util.concurrent.atomic 應用:
    import java.util.concurrent.atomic.*;
    
    public class Demo{
    
     public static void main(String[] args){
      
      AtomicInteger ai = new AtomicInteger(5);
      
      if (ai.compareAndSet(5,42)){
       System.out.println("The current value: " + ai.get());
       System.out.println("Replaced 5 with 42");
      }
     }
    }
    

    Concurrent I/O 的應用:
    public class MultiThreadedClientMain {
        public static void main(String[] args){
            ExecutorService es = Executors.newCachedThreadPool();
            Map < RequestResponse,Future < RequestResponse >> callables = 
                                                         new HashMap<>();
            
            String host = "localhost";
            for (int port = 10000; port <  10010 ; port++){
                RequestResponse lookup = new RequestResponse(host, port);
                NetworkClientCallable callable = 
                                      new NetworkClientCallable(lookup);
                Future future = es.submit(callable);
                callables.put(lookup, future);
            }
            es.shutdown();
            try{
                es.awaitTermination(5, TimeUnit.SECONDS);
            } catch(InterruptedException ex){
                System.out.println("Stopped waiting early");
            }
            
            for (RequestResponse lookup : callables.keySet()){
                Future future = callables.get(lookup);
                try {
                    lookup = future.get();
                    System.out.println(lookup.host + ":" + lookup.port + 
                         " " + lookup.response);
                } catch (ExecutionException | InterruptedException ex){
                    System.out.println("Error talking to " + lookup.host +
                            ":" + lookup.port);
                }
            }
        }
    }
    

    public class RequestResponse {
        public String host;
        public int port;
        public String response;
        
        public RequestResponse(String host, int port){
            this.host = host;
            this.port = port;
        }
    }
    

    public class NetworkClientCallable implements Callable < RequestResponse > {
        private RequestResponse lookup;
        
        public NetworkClientCallable(RequestResponse lookup) {
            this.lookup = lookup;
        }
    
        @Override
        public RequestResponse call() throws IOException {
            try (Socket sock = new Socket(lookup.host, lookup.port);
                 Scanner scanner = new Scanner(sock.getInputStream());){
                lookup.response = scanner.next();
            }
            return lookup;
        }   
    }
    

    2015年8月28日 星期五

    Java 迴圈語法

    Java 迴圈語法:while 、do/while 、for 迴圈

    While 迴圈簡單範例:
    public class TaxDemo{
    
     public static void main(String[] args){
    
      double balance = 500;
      double taxRate = 0.07;
      int years = 0;
      
      while (balance <= 1000){
      
       balance = (balance * (1+0.07));
       years++;
      
      }
      System.out.printf("Year %d: %.2f",years,balance);
     }
    } 
    

    修改一下 Elevator 的程式:(其他部份,請參考這裡!)
    public class Elevator{
    ...omit....
    
    //判斷是否到達所須要的樓層
     public void goToFloor(int desiredFloor){
      while (this.currentFloor != desiredFloor){
       if (this.currentFloor > desiredFloor){
        this.goDown();
       } else {
        this.goUp();
       }
      }
      System.out.println("Arrived..");
      this.openDoor();
     }
    
    ..... omit ......
    
    

    執行的程式也一併修改一下:
    import java.util.Scanner;
    
    public class ElevatorDemo{
    
     public static void main(String[] args){
     
      Elevator myElevator = new Elevator();
      Scanner scanner = new Scanner(System.in);
      
      System.out.print("請選擇樓層(1~10):");
      myElevator.doorOpen = true;
      myElevator.goToFloor(scanner.nextInt()); 
      
     }
    }
    
    

    for 迴圈用法:(99乘法表)
    public class table99{
    
     public static void main(String[] args){
     
      for (int i = 1,j = 1; i < 10 ; i=(j==9)?(i+1):(i),j=(j==9)?(1):(j+1)){
       System.out.printf("%d*%d=%d\t",i,j,(i*j));
       if (j==9){
        System.out.println();
       }
      }
     }
    }
    

    continue 與 break 也來湊熱鬧:
    import java.util.*;
    
    public class ScoreClassDemo{
    
     public static void main(String[] args){
     
      Scanner scanner = new Scanner(System.in);
      ArrayList pass = new ArrayList();
      ArrayList noPass = new ArrayList();
      
      int account = 0;
      int score = 0;
      
      while (true){
       System.out.printf("請輸入第 %d 位學生成績:",(account + 1));
       score = scanner.nextInt();
       if ((score > 100)||(score <= -2)){
        System.out.println("重新輸入");
        continue;
       } else if (score == -1){
        break;
       } else if ( score >= 60){
        pass.add(score);
       } else {
        noPass.add(score);
       }
       account++;
      }
      System.out.println("及格人數: " + pass.size());
     }
    }
    

    2015年8月26日 星期三

    Java 陣列的使用

    Java 一維陣列的應用:
    import java.util.Scanner;
    
    public class OneArrayDemo{
    
     public static void main(String[] args){
     
      Shirt[] myShop = new Shirt[10];
      Scanner scanner = new Scanner(System.in);
      String temp1;
      
      myShop[0] = new Shirt();
       
      System.out.print("Please input the description: ");
      temp1 = scanner.nextLine();
      myShop[0].description = temp1;
      
      System.out.print("Please input the ShirtID: ");
      myShop[0].shirtID = scanner.nextInt();
        
      System.out.print("Please input the colorCode: ");
      temp1 = scanner.next();
      myShop[0].colorCode = temp1.charAt(0);
      
      System.out.print("Please input the price: ");
      myShop[0].price = scanner.nextDouble();
      
      myShop[0].displayInformation();
      
     }
    }
    

    Shirt 請參考另一篇文章

    二位陣列使用方式:
    import java.util.Scanner;
    
    public class TwoArrayDemo{
    
     public static void main(String[] args){
      
      int courses = 3;
      int students = 10;
      int[][] scores = new int[courses][students];
      
      System.out.println("請輸入數學科分數:");
      TwoArrayDemo.inputScore(1,students,scores);
      System.out.println();
      System.out.println("請輸入國文科分數:");
      TwoArrayDemo.inputScore(2,students,scores);
      System.out.println();
      System.out.println("請輸入英文科分數:");
      TwoArrayDemo.inputScore(3,students,scores);
      System.out.println();
      System.out.println("每位學生的平均分數:");
      TwoArrayDemo.avgScore(courses,students,scores);
     }
     
     public static void inputScore(int course,int students, int[][] scores){
      Scanner scanner = new Scanner(System.in);
      int sum = 0;
      for (int i = 0; i < students; i++){
       System.out.printf("請輸入第 %d 位學生成績:",(i+1));
       scores[course-1][i] = scanner.nextInt();
       sum += scores[course-1][i];
      }
      System.out.println("本科平均分數:" + ((double)sum)/students);
     }
     
     public static void avgScore(int courses,int students,int[][] scores){
      
      int temp = 0;
      for (int i = 0 ; i < students ; i++){
       for (int j = 0 ; j < courses ; j++){
        temp += scores[j][i];
       }
       System.out.printf("第 %d 位學生平均分數: %.2f\n",i, ((double)temp)/courses);
       temp = 0;
      }
     }
    }
    


    ArrayList 的使用方式:
    import java.util.*;
    
    public class ArrayListDemo{
    
     public static void main(String[] args){
     
      ArrayList myList = new ArrayList();
    
      myList.add("Peter");
      myList.add("James");
      myList.add("Piggy");
      myList.add("Janeson");
      myList.add("Tordy");
      
      myList.remove(0);
      myList.remove(myList.size()-1);
      myList.remove("Piggy");
      
      System.out.println(myList);
     }
    }
    

    2015年8月24日 星期一

    Java 決策判斷語法

    Java 的關係運算子:== 、!= 、 > 、 >= 、 < 、 <= 、equals() ... 判斷的語法: if 、 if/else 、switch
    先來點熱身的:
    public class Employees{
     
     public String name1 = "Fred Smith";
     public String name2 = "Joseph Smith";
     
     public static void main(String[] args){
      Employees myEmployee = new Employees();
      myEmployee.areNamesEqual();
     }
     
     public void areNamesEqual(){
     
      //比較兩者是否為同一物件
      if ( name1 == name2 ){
       System.out.println("Same Object.");
      } else {
       System.out.println("Different Object.");
      }
     
      //比較物件內容值是否相同
      if (name1.equals(name2)){
       System.out.println("Same Name.");
      } else {
       System.out.println("Different Name.");
      }
     }
    }
    
    以電梯的類別來示範 if/else 以及 nested if/else 用法:
    public class Elevator{
    
     public boolean doorOpen = false;
     public int currentFloor = 1;
     public final int TOP_FLOORS = 10;
     public final int MIN_FLOORS = 1;
     
     //開門的動作
     public void openDoor(){
      System.out.println("Opening Door ... ");
      doorOpen = true;
      System.out.println("Door is opened!");
     }
     
     //關門的動作
     public void closeDoor(){
      System.out.println("Closing Door ... ");
      doorOpen = false;
      System.out.println("Door is closed!");
     }
     
     //電梯向上
     public void goUp(){
      if ( currentFloor >= TOP_FLOORS){
       System.out.println("Cannot go Up!");
      } else {
        if (doorOpen){
     closeDoor();
        }
    
       System.out.println("Going Up one floor !");
       currentFloor++;
       System.out.println("Floor: " + currentFloor);
      }
     }
    
    //電梯向下
     public void goDown(){
      if ( currentFloor <= MIN_FLOORS){
       System.out.println("Cannot go Down!");
      } else {
    
       if (doorOpen){
     closeDoor();
       }
    
       System.out.println("Going Down one floor !");
       currentFloor--;
       System.out.println("Floor: " + currentFloor);
      }
     }
    }
    
    執行看看....
    public class ElevatorDemo{
    
     public static void main(String[] args){
     
      Elevator myElevator = new Elevator();
      
      myElevator.openDoor();
      myElevator.closeDoor();
      myElevator.goDown();
      myElevator.goUp();
      myElevator.goUp();
     }
    }
    
    
    一種 Low Low 的範例:
    import java.util.Scanner;
    
    public class MonthDemo{
    
     public static void main(String[] args){
     
      Scanner scanner = new Scanner(System.in);
      System.out.print("請輸入月份:");
      int month = scanner.nextInt();
      if ( month == 1 || month == 3 ||month == 5 ||
       month == 7 || month == 8 || month == 10 ||
       month == 12 ){
        System.out.println("本月份有31天!");
       } else if (month == 2){
        System.out.println("本月份有28天!");
       } else if (month == 4 || month == 6 ||
       month == 9 || month == 11){
        System.out.println("本月份有30天!");
       }else{
        System.out.println("invalid days !");
      }
      
     }
    }
    

    一種好的範例:
    import java.util.Scanner;
    
    public class SwitchDemo{
    
     public static void main(String[] args){
     
      Scanner scanner = new Scanner(System.in);
      System.out.print("請輸入月份:");
      int month = scanner.nextInt();
      switch (month){
       case 1:
       case 3:
       case 5:
       case 7:
       case 8:
       case 10:
       case 12:
        System.out.println("本月份有31天!");
        break;
       case 2:
        System.out.println("本月份有28天!");
        break;
       case 4:
       case 6:
       case 9:
       case 11:
        System.out.println("本月份有30天!");
        break;
       default:
        System.out.println("invalid days !");
      }
      
     }
    }
    

    2015年8月23日 星期日

    利用 JDBC 撈取資料庫內容

    利用 JDBC 撈取資料庫的方式:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class ConnectionDemo {
        public static void main(String[] args)
                      throws ClassNotFoundException{
            
            Class.forName("com.mysql.jdbc.Driver");
            
            String url = "jdbc:mysql://localhost:3306/directory"; 
            String dbaccount = "directory";
            String dbpassword = "a123456";
            
            try(Connection conn = DriverManager.getConnection(url,
                     dbaccount, dbpassword);
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)){
                              
              //列出資料表欄位資料
                int numCols = rs.getMetaData().getColumnCount();
                String[] colsName = new String[numCols];
                String[] colsType = new String[numCols];
                for (int i = 0; i < numCols; i++){
                    colsName[i] = rs.getMetaData().getColumnName(i+1);
                    colsType[i] = rs.getMetaData().getColumnTypeName(i+1);
                }
                System.out.println("Numbers of columns returned:  "
                                   + numCols);
                System.out.println("Column names/types returned: ");
                 for (int i = 0; i < numCols; i++){
                     System.out.println( colsName[i] + " : " + colsType[i]);
                 }
                 
                 //列出資料表所裝填的內容
                System.out.println(colsName[0] +"\t\t" + colsName[1] +
                                  "\t" +colsName[2]);
                while (rs.next()){
                   String rsID = rs.getString(colsName[0]);
                   String rsUserName = rs.getString(colsName[1]);
                   String rsEmail = rs.getString(colsName[2]);
                   System.out.println(rsID + "\t\t" + rsUserName +
                                                    "\t\t"+rsEmail);
    
            } catch (SQLException ex) {
               System.out.println("資料庫連結失敗....");
            }
        }
    }
    

    JDBC 連結資料庫

    利用 JDBC 與資料庫連結:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class ConnectionDemo {
        public static void main(String[] args)
                      throws ClassNotFoundException{
            
            Class.forName("com.mysql.jdbc.Driver");
            
            String url = "jdbc:mysql://localhost:3306/directory"; 
            String dbaccount = "directory";
            String dbpassword = "a123456";
            
            try(Connection conn = DriverManager.getConnection(url,
                     dbaccount, dbpassword)){
               
                if (!conn.isClosed()){
                    System.out.println("資料庫連結成功....");
                }
                
            } catch (SQLException ex) {
               System.out.println("資料庫連結失敗....");
            }
        }
    }
    

    MySQL 的範例資料庫 directory,可以利用下列語法建立起來:
    
    CREATE DATABASE  IF NOT EXISTS `directory`;
    USE `directory`;
    
    DROP TABLE IF EXISTS `users`;
    CREATE TABLE `users` (
      `no` int(11) NOT NULL AUTO_INCREMENT,
      `userName` varchar(100) NOT NULL,
      `userEmail` varchar(100) NOT NULL,
      PRIMARY KEY (`no`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    LOCK TABLES `users` WRITE;
    INSERT INTO `users` VALUES (1,'test','test@localhost'),
           (2,'hello','hello@localhost.domain'),(3,'world','world@test.123');
    UNLOCK TABLES;
    
    

    2015年8月22日 星期六

    volatile 與 synchronized 使用

    volatile 範例:
    public class ExampleRunnable implements Runnable{
        private volatile int j;
        @Override
        public void run() {
            
            for (j = 0; j < 10; j+=2){
                System.out.println("j = " + j);
            }
        }   
    }
    

    Demo 一下,看看執行結果:
    public class ThreadDemo {
        public static void main(String[] args){ 
    
            ExampleRunnable er1 = new ExampleRunnable();
    
            Thread t1 = new Thread(er1);
            Thread t2 = new Thread(er1);
            Thread t3 = new Thread(er1);
            t1.start();
            t2.start();
            t3.start();
            
        }
    }
    


    syhchronized 範例:
    
    

    2015年8月21日 星期五

    Java 物件的利用

    Java 物件的新增與使用:

    Shirt 類別程式,請參考另一篇文件

    public class Demo2{
    
      public static void main(String[] args){
      
        Shirt myShirt = new Shirt();
        Shirt yourShirt = new Shirt();
        
        myShirt = yourShirt;
        
        myShirt.colorCode = 'R';
        yourShirt.colorCode = 'G';
        
        System.out.println("Shirt color: " + myShirt.colorCode);
      
      }
    }
    

    String 類別的利用:
    public class StringDemo{
    
     public static void main(String[] args){
     
      String myString = "Hello";
      myString = myString.concat("! This is my First program!");
      myString = myString + "\n Please fill the screen !!".trim();
      
      myString = myString + "\nHAHA..".toLowerCase();
      System.out.println(myString);
      
      myString = (myString + "\nHAHA..").toLowerCase();
      System.out.println(myString);
      
      
      int stringLength = myString.length();
      System.out.println("Length : " +  stringLength);
      
      String partString = myString.substring(6,20);
      System.out.println(partString);
      
      boolean endWord = myString.endsWith("ha..");
      System.out.println("The results: " + endWord);
     
     }
    }
    

    StringBuilder 類別的利用:
    
    public class StringBuilderDemo{
    
     public static void main(String[] args){
     
      StringBuilder myString = new StringBuilder("Hello,");
      myString.append(" Java!");
      
      String h1 = "Today is Monday!";
      String h2 = "World is a good place!!";
      
      myString.insert(6, h1);
      
      System.out.println("Total length: " + myString.length());
      
      myString.delete(6,12);
      myString.replace(13,19,h2);
      
      System.out.println(myString);
     }
    }
    
    

    Servlet 第一支程式

    Servlet 第一支程式:
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet(name="HelloServlet", urlPatterns={"/hello.view"},
                loadOnStartup=1)
    public class HelloWorld extends HttpServlet {
    
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) {
                
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet HelloWorld</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet HelloWorld at "
                   + request.getContextPath() + "</h1>");
                out.println("</body>");
                out.println("</html>");
            }
        }
    
        
        @Override
        protected void doGet(HttpServletRequest request, 
                             HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        
        @Override
        protected void doPost(HttpServletRequest request, 
                              HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    }
    

    index.html 可以寫成下列方式 ...
    <!DOCTYPE html>
    <html>
        <head>
            <title>TODO supply a title</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body>
            <div>TODO write content</div>
        </body>
    </html>
    

    網址:
    http://localhost:8080/ServletDemo1/hello.view
    

    2015年8月19日 星期三

    Java 基本運算子的使用

    Java 的算術運算子:+ - * / %
    public class Person{
    
     public int ageYears = 32;
     
     public void calculateAge(){
     
      int ageDays = ageYears * 365;
      long ageSeconds = ageYears * 365 * 24L * 60 * 60;
     
      System.out.println("You are " + ageDays + " days old.");
      System.out.println("You are " + ageSeconds + " seconds old.");
     }
    }
    
    執行它:
    public class PersonDemo{
    
     public static void main(String[] args){
     
      Person peter = new Person();
      peter.calculateAge();
     
     }
    }
    

    配合 java.util.Scanner 物件來做為輸入數量的參考:
    import java.util.Scanner;
    
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt();
      myShirt.shirtID = 100;
      myShirt.colorCode = 'B';
      myShirt.price = 45.12;
      myShirt.description = "45周年紀念衫";
      
      myShirt.displayInformation();
     
      Scanner scanner = new Scanner(System.in);
      System.out.print("請輸入購買件數:");
      int input = scanner.nextInt();
      System.out.println("總價:" + input*myShirt.price);
     
     }
    }
    

    Java 基本資料型態

    Java 變數的資料型態分兩種:基本資料型態類別資料型態

    基本資料型態:
    • 整數型態:byte (8 bits)、short (16 bits)、int (32 bits)、long (64 bits)
    • 浮點數型態:float ( 32 bits) 、double (64 bits)
    • 文字型態: char (16 bits)
    • 邏輯型態:boolean 

    Java 物件內的變數宣告

    Java 物件內的變數分成 Fields 與 Local Variables ,兩者有不同的地方:
    public class Shirt{
    
     //這是 Fields
     public int shirtID = 0;
     public String description = "-----";
     public char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
     public double price = 0.0;
     
     //顯示 Shirt 相關資料
     public void displayInformation(){
     
      System.out.println("Shirt ID: " +  shirtID);
      displayDescription(this.description);
      System.out.println("Shirt Color: " + colorCode);
      System.out.println("Shirt's price: " + price);
     }
    
     public static void displayDescription(String d1){
       //這是Local Variables
       String displayString = "";
       displayString = "Shirt description: " + d1;
       System.out.println(displayString);
     } 
    }
    
    Java 物件的變數名稱,可以利用物件來指派與修改!
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt();
      myShirt.shirtID = 100;
      myShirt.colorCode = 'B';
      myShirt.price = 45.12;
      myShirt.description = "45周年紀念衫";
      
      myShirt.displayInformation();
     
     }
    }
    

    2015年8月17日 星期一

    Java 物件概要

    Java 類別的形成:
    public class Shirt{
    
     public int shirtID = 0;
     public String description = "-----";
     public char colorCode = 'U' ; //R=red,G=green,B=blue,W=white
     public double price = 0.0;
     
     //顯示 Shirt 相關資料
     public void displayInformation(){
     
      System.out.println("Shirt ID: " +  shirtID);
      System.out.println("Description: " + description);
      System.out.println("Shirt Color: " + colorCode);
      System.out.println("Shirt's price: " + price);
     }
    }
    



    Java 物件的利用:
    public class Demo{
    
     public static void main(String[] args){
     
      Shirt myShirt = new Shirt();
      myShirt.displayInformation();
     
     }
    }
    


    Java 基本程式撰寫

    Java 基本程式寫作方式:(通常第一支程式都是 Hello World !!)

    public class HelloWorld {
    
        public static void main (String[] args) {
            System.out.println("Hello, world!");
        }
    }
    

    • class <類別名稱>: 因為 Java 語言是物件導向語言,所以都是以 class 開頭來撰寫程式!而類別名稱,則是給這個類別命名,方便其他程式的呼叫!
    • public ... : 表示公開的權限!Java 語言權限,是代表其安全機制的由來,權限共分四級!利用適當的權限值,可確保程式被利用時的安全性!
    • public static void main(String[] args){...} : 表示 Java 程式開始執行的進入點。
    • System.out.println(...) :表示在文字介面視窗中,印出所需要的文字!
    • ; 分號表示程式表示式結束的描述,除了使用 {} 之外,每行 Java 程式描述句結束後,都應加上此符號!

    接下來,將檔案存成與<類別名稱>相同的 <類別名稱.java> 檔案,例如本程式應存成 HelloWorld.java 檔案!
    之後,將該檔案進行編譯,變成可執行的 Class 檔案!例如:
    C:\workspace\test1> javac HelloWorld.java

    最後執行該 Java 程式,應使用 Java 執行該 class 檔案!例如:
    C:\workspace\test1> java HelloWorld

    JDK 安裝與設定

    Java 語言的撰寫,最重要的一件事,就是準備好工具!而最重要的工具,就是 JDK(Java Development Kits) !JDK 安裝與設定如下:
    1. Oracle 官方下載 JDK!
    2. 進行「下一步」到底的安裝!
    3. 在電腦的環境設定中,設定 Path 環境項目,加入 Java bin 的目錄!
    4. 利用下列指令測試:
    • javac  -version
    • java  -version

    另一種重要的工具,就寫程式的軟體了!通常,利用文字編輯器即可!以下提供常見工具:
    1. Notepad++ : 純文字編輯器!台灣人寫的,給正要入門的新手,最好的寫作平台!
    2. NetBean : Oracle 官方的 IDE (Integrated Development Environment),簡單、易用!
    3. Eclipse : 業界常用!有多方開發的整合套件,方便開發任何 Java 程式語言!

    最後一種常用工具: Java API Documents !! (Java SE 8)因為,沒人可以記得住 Java 所有可用 API ,所以,查文件也是一種功力的表現!

    本站重新開張

    本站重新開張!

    幾經思考之後,發現最原始的寫作方式,是比較適合像小弟這種老人的!
    經過大幅刪了之前的東西之後,發現了新的空間與想法!有如珍瓏琪局般的巧妙,在砍除已方的棋子之後,豁然開朗的產生新局!

    也是該這麼整理了!

    2015-08-17