2011年10月24日 星期一

驗證圖形驗證碼

index.jsp ----->主頁面

<%@ page language="java" contentType="text/html; charset=BIG5"%>

<form method="post" action="Verification.jsp">
    <img src="dynamicImage"/><br/>
    <input type="text" name="value"></input>
    <input type="submit"></input>
</form>


Verification.jsp ----->驗證

<%@ page language="java" contentType="text/html; charset=big5"%>

<%
    if( request.getParameter("value").equals(session.getAttribute("number")) ){
        out.print("驗證碼正確");
    }else{
        out.print("驗證碼錯誤");
    }
%>


DynamicImage.java ---->產生動態圖形驗證碼

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DynamicImage extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setContentType("image/jpeg");

        BufferedImage bi = new BufferedImage(50,30,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, 50, 30);
        g2d.setColor(Color.black);
        g2d.drawRect(5, 5, 40, 20);

        StringBuilder sbl = new StringBuilder();
        while(sbl.length() < 4){
            sbl.append(Integer.toString((int)(Math.random() * 9)));
        }

        session.setAttribute("number", sbl.toString());
  
        g2d.setFont(new Font("Default",Font.BOLD,13));
        g2d.drawString(sbl.toString(), 10, 20);
  
        for(int i = 0; i < 20; i++){
            int x = (int)(Math.random() * 40) + 5;
            int y = (int)(Math.random() * 20) + 5;
   
            g2d.fillOval(x, y, 1, 1);
        }
  
        ServletOutputStream sos = response.getOutputStream();
  
        Iterator ite = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter iw = (ImageWriter)ite.next();
  
        ImageOutputStream ios = ImageIO.createImageOutputStream(sos);
        iw.setOutput(ios);
        iw.write(bi);
        ios.flush();
        sos.close();
}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>DynamicImage</servlet-name>
    <servlet-class>com.morty.dynamicimage.DynamicImage</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DynamicImage</servlet-name>
    <url-pattern>/dynamicImage</url-pattern>
  </servlet-mapping>

</web-app>

2011年10月23日 星期日

動態產生密碼圖片

DynamicImage.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DynamicImage extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        BufferedImage bi = new BufferedImage(50,30,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, 50, 30);
        g2d.setColor(Color.black);
        g2d.drawRect(5, 5, 40, 20);
  
        StringBuilder sbl = new StringBuilder();
        while(sbl.length() < 4){
                sbl.append(Integer.toString((int)(Math.random() * 9)));
        }
  
        g2d.setFont(new Font("Default",Font.BOLD,13));
        g2d.drawString(sbl.toString(), 10, 20);
  
        for(int i = 0; i < 20; i++){
                int x = (int)(Math.random() * 40) + 5;
                int y = (int)(Math.random() * 20) + 5;
   
                g2d.fillOval(x, y, 1, 1);
        }
  
        response.setContentType("image/jpeg");
        ServletOutputStream sos = response.getOutputStream();
  
        Iterator ite = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter iw = (ImageWriter)ite.next();
  
        ImageOutputStream ios = ImageIO.createImageOutputStream(sos);
        iw.setOutput(ios);
        iw.write(bi);
        ios.flush();
        sos.close();
    }
}

2011年10月3日 星期一

BMI指數

BMI.jsp


<%@ page contentType="text/html; charset=big5"%>

<form method="post" action="BMI.jsp">
    性別:<select name="sex">
        <option></option>
        <option value="man">男</option>
        <option value="woman">女</option>
    </select><br>
    身高(公分):<input type="text" name="height" style="width:5%"/><br>
    體重(公斤):<input type="text" name="weight" style="width:5%"/><br>
    <input type="submit" value="送出">
</form>

<%
    String height = request.getParameter("height");
    String weight = request.getParameter("weight");
    if(height == null || weight == null){
        height = "0.0";
        weight = "0.0";
    }
    String url = "count.jsp?height=" + height + "&weight=" + weight;
%>

<jsp:include page="<%=url%>"></jsp:include>


count.jsp


<%@ page contentType="text/html; charset=big5" %>
<%@
    page import="java.io.*"
%>

<%
    String exponent = "";
    String standard = "";
    int num = 0;
    double h=0.0,w=0.0;

    h = Double.parseDouble(request.getParameter("height")) / 100;
    w = Double.parseDouble(request.getParameter("weight"));

    double ans = w / (Math.pow(h, 2)); //體重 (kg) / 身高 (m)的平方

    if( Double.isNaN(ans) == false){
        exponent = Long.toString(Math.round(ans));
        num = Integer.parseInt(exponent);

        /*
            男性: (身高cm-80)×70﹪=標準體重
            女性: (身高cm-70)×60﹪=標準體重
        */
        if(request.getParameter("sex").equals("man")){
            standard = Double.toString(((h*100)-80)*0.7) + " 公斤";
        }else{
            standard = Double.toString(((h*100)-70)*0.6) + " 公斤";
        }
    }

    String str = "";

    //結果
    if( num == 0){
        str = "";
    }else if( num < 18.5 ){
        str = "體重過輕";
    }else if( num > 18.5 && num < 24){
        str = "正常範圍";
    }else if( num >= 24 && num < 27){
        str = "體重過重";
    }else if( num >= 27 && num < 30){
        str = "輕度肥胖";
    }else if( num >= 30 && num < 35 ){
        str = "中度肥胖";
    }else{
        str = "重度肥胖";
    }

%>

<p>BMI 指數:<%=exponent%></p>

<p>結果:<%=str%></p>

<p>標準體重:<%=standard%></p>


web.xml


<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

    <welcome-file-list>
        <welcome-file>BMI.jsp</welcome-file>
    </welcome-file-list>
</web-app>

2011年6月6日 星期一

Java LCS 最長共同子序列


import java.util.Scanner;

public class LongComSub {
    public static String str1;
    public static String str2;
    public static String result;//記錄共同子序列
 
    public static char [] cha1;
    public static char [] cha2;
 
    public static int [][] array;//LCS表格
    public static String [][] prev;//記錄計算方向
 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
  
        System.out.print("輸入第一個字串: ");
        str1 = sc.nextLine();
        System.out.print("輸入第二個字串: ");
        str2 = sc.nextLine();
  
        /*str1為短字串  str2為長字串*/
        if(str1.length() > str2.length()){
              String value = str1;
              str1 = "0" + str2;
              str2 = "0" + value;
        }
        else{
              str1 = "0" + str1;
              str2 = "0" + str2;
        }
 
        /*設定陣列長度*/
        array = new int[str1.length()][str2.length()];
        prev = new String[str1.length()][str2.length()];
  
        /*將字串轉換為陣列*/
        cha1 = str1.toCharArray();
        cha2 = str2.toCharArray();
  
        setZero();
  
        countLCS();

        foundValue(cha1.length-1,cha2.length-1);
  
        System.out.print("最長共同子序列: ");
        StringBuffer sb = new StringBuffer(result.substring(4));
        System.out.print(sb.reverse());
    }
 
    /*將 array[x][0] 和 array[0][x] 都設為 0*/
    public static void setZero(){
        for(int i = 0; i < str1.length(); i++){
              array[i][0] = 0;
        } 
        for(int i = 0; i < str2.length(); i++){
              array[0][i] = 0;
        }
    }
 
    /*計算並製作LCS表格*/
    public static void countLCS(){
        System.out.print("  ");
        for(int u = 0; u < cha2.length; u++){
              System.out.print(cha2[u] + " ");
        }
        System.out.println();

        for(int i = 1; i < cha1.length; i++){
              System.out.print(cha1[i] + " ");
              for(int j = 1; j < cha2.length; j++){
                    if( i == 0 || j == 0 ){
                          System.out.print(array[i][j] + " ");
                          continue;
                    }
                    if( cha1[i] == cha2[j] ){
                          array[i][j] = array[i-1][j-1] + 1;
                          prev[i][j] = "左上方";
                          System.out.print(array[i][j] + " ");
                    }
                    else if( array[i-1][j] < array[i][j-1]){
                          array[i][j] = array[i][j-1];
                          prev[i][j] = "左方";
                          System.out.print(array[i][j] + " ");
                    }
                    else{
                          array[i][j] = array[i-1][j];
                          prev[i][j] = "上方";
                          System.out.print(array[i][j] + " ");
                    }
              }
        }
    }
 
    /*找出LCS值*/
    public static void foundValue(int a,int b){
        if(a == 0 && b == 0){
              System.exit(0);
        }
  
        if(prev[a][b] == "左上方"){
              //String初始值null,所以會從null開使加字串
              result += Character.toString(cha1[a]);
              foundValue(a-1,b-1);
        }
        else if(prev[a][b] == "上方"){
              foundValue(a-1,b);
        }
        else if(prev[a][b] == "左方"){
              foundValue(a,b-1);
        }
    }
}


沒有考慮到時間複雜度以及記憶體問題唷

2011年5月26日 星期四

Java 偶基數判斷

一般的比較法

int a = 3;
int b = 4;
 
System.out.println(a%2==0?"a是偶數":"a是奇數");
System.out.println(b%2==0?"b是偶數":"b是奇數");


較快速的比較法

int a = 3;
int b = 4;
 
System.out.println((a&1)==0?"a是偶數":"a是奇數");
System.out.println((b&1)==0?"b是偶數":"b是奇數");


3 & 1 = 0011 & 0001 = 1
4 & 1 = 0100 & 0001 = 0

用%的話就顯得比&還要慢了

來源

2011年5月5日 星期四

Java 費氏數列


import java.util.Scanner;

public class Fibonacci {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("輸入數列大小: ");
        int a = sc.nextInt();
        long [] fin = new long[a];
        fin[0] = 1;
        fin[1] = 1;
  
        for(int i = 2; i < a; i++){
             fin[i] = (fin[i-1] + fin[i-2]);
        }
  
        for(long b : fin ){
             System.out.print(b + " ");
        }
  
    }
}

2011年5月3日 星期二

查詢本機IP


import java.net.*;

public class LookIP {
   public static void main(String[] args){
      try{
         InetAddress host = InetAddress.getLocalHost();
         System.out.println("網域名稱: " + host.getHostName());
         System.out.println("IP位址: " + host.getHostAddress());
      }catch(Exception e){
         e.printStackTrace();
      }
   }
}


2011年3月30日 星期三

Java 算一算每行有幾個字

Word的定義是連續的字元(A~Z,a~z)所組成的字。
ASCII 字元表

輸入說明:
asd....asd
This is a book.

輸出說明:
2
4

import java.util.*;

public class HowManyWorld {
   public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      String str;
      StringBuffer stb;
      int a,b;
      char c;
  
      while(sc.hasNext()){
         str = sc.nextLine();
         stb = new StringBuffer(str);
         a = 0;
         b = 0;
  
         for(int i = 0; i < str.length(); i++){
            c = stb.charAt(i);
            if( (c >= 65 && c <= 90) || (c >= 97 && c <= 122) ){
                b++;
                continue;
            }
            else if((b >= 1) && (i > 0 || c <= 64 || (c >= 91 && c <= 96) || c >= 123)){
                b = 0;
                a++;
            }
         }
         if( b >= 1 ){
            a++;
         }
         System.out.println(a);
      }
   }
}

2011年3月28日 星期一

Java 因數分解


import java.util.Scanner;

public class Factorization {
   public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      StringBuffer str;
      Boolean zero;
      long a ;
      int b, index;
      String ss = "S";

      while(sc.hasNext()){
        zero = false;
        str = new StringBuffer();
        a = sc.nextLong();
        b = (int)Math.sqrt(a) + 1;
   
        for(long i = 2; i <= b; i++){
            int c = 0;
            if(a == 2){
               str.append(a + " * ");
               break;
            }
            for(long j = i; j <= b; j *= (zero == true ? i : 1)){
                if( a % j == 0){
                   str.append(j);
                   str.append(" * ");
                   a /= j;
                   c++;
                   ss = Long.toString(j) + " * ";
                   zero = false;
                }
                else{
                   if( c >= 2){
                      str.delete(str.indexOf(Long.toString(j)),str.lastIndexOf("*")+2);
                      str.append(Long.toString(j) + "^" + Integer.toString(c) + " * ");
                   }
                   c = 0;
                   zero = true;
                }
            }
        }
        index = str.length();

        if(index == 0){
            str.append(a);
        }
        else{
            if(ss.equals(str.toString()) == true){
               str.append(" * " + a);
            }
            str.delete(index-3,index);
        }
        System.out.println(str);
      }
   }
}

2011年3月22日 星期二

Java 阿拉伯數字轉國字

最大顯示到拾億,也就是10位阿拉伯數字


import java.util.Scanner;

public class Chinese {
    static String [] chineseNumber = {"零","壹","貳","參","肆","伍","陸","柒","捌","玖"};
    static String [] chineseUnit = {"","拾","佰","仟","萬","拾萬","佰萬","仟萬","億","拾億"};
    static StringBuffer str;
    static Long money;
    static String input;
    static int index;
    static boolean naZero;
    static Scanner sc = new Scanner(System.in);
     
    public static void main(String args[]){
        while( sc.hasNext() ){
            str = new StringBuffer();
            money = sc.nextLong();
            input = money.toString();
            index = input.length();
            naZero = false;

            for( char a : input.toCharArray() ){
                index--;

                if( a > '0' ){
                    if( naZero ){
                        str.append(chineseNumber[0]);
                        naZero = false;
                    }
                    str.append(chineseNumber[(int)(a-'0')]+chineseUnit[index]);
                }
                else{
                    naZero = true;
                }
    
                String b = chineseUnit[index <= 7 ? 4 : 8];
                    int c = str.indexOf(b);
                    int d = str.lastIndexOf(b);
                    if( c == d ){
                        continue;
                    }
                    else{
                        str.deleteCharAt(c);
                    }
                }
   
                if( str.length() == 0 ){
                    str.append(chineseNumber[0]);
                }
   
                System.out.println(str);
        }
    }
}