2013年1月29日 星期二

麥肯錫邏輯思考力

Android AlertDailog 應用


由mydialog1 複製過來,重新命名為mydialog2,並針對 com.example.mydialog1 
refactor 為 com.example.mydialog2。

在showDialog()函數中,定義字串陣列 String[] items = {"Android", "iOS", "Win8", "Other"}; 按下選單時觸發builder.setItems 函數,


builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
})

詳細程式如下



package com.example.mydialog2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mydialog1.R;

public class MainActivity extends Activity {
private Button click1;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click1=(Button) findViewById(R.id.click1);
click1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog();
}
});


}

private void showDialog()
{
AlertDialog dialog1;
AlertDialog.Builder builder=new AlertDialog.Builder(this);
String[] items = {"Android", "iOS", "Win8", "Other"};

builder.setTitle("請選擇");
builder.setCancelable(false);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "" + which, Toast.LENGTH_SHORT).show();
}
});
dialog1=builder.create();
dialog1.show();
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}






2013年1月28日 星期一

JAVA 連結 ACCESS 範例



本程式主要透過ODBC連結ACCESS,故須先設計一資料庫MFG,其中Table1 欄位如下


 ODBC 設定如下





主要JAVA 程式碼如下


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Login;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;


/**
 *
 * @author jackylin
 */
public class login {        
            Connection Conn;            
            Statement st;
            ResultSet rs;
            JFrame f=new JFrame("Login ");
            JLabel l=new JLabel("User:");
            JTextField t=new JTextField(10);
            JLabel l1=new JLabel("Pass:");
            JTextField t1=new JTextField(10);
            JButton b=new JButton("Login");
            JPanel p=new JPanel();
         
          public login()
        {
                connect();
                frame();
        }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
            new login();            
            System.out.print("Hello db");    
    }

    private void connect() {
        
        try {
                String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
/*你可以使用Class的靜態forName()方法實現動態加載類別
透過java.lang.Class類別的forName()來載入並向DriverManager註冊JDBC
驅動程式(驅動程式會自動透過 DriverManager.registerDriver()方法註冊)*/

                Class.forName(driver);
                String db="jdbc:odbc:db1";
/*要連線資料庫,我們可以從DriverManager要求並取得Connection物件,它代表資
 料庫連線物件*/
                Conn=DriverManager.getConnection(db);
                st=Conn.createStatement();                              
                } catch (ClassNotFoundException | SQLException ex) {
                }       
         }

    private void frame() {
            f.setSize(180,200);            

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
            p.add(l);
            p.add(t);
            p.add(l1);
            p.add(t1);
            p.add(b);   
            f.add(p);
             b.addActionListener(
                     new ActionListener()
                     {
                                //實作
         public void actionPerformed(ActionEvent e) {
         String user=t.getText().trim();
         String pass=t.getText().trim();
         String sql="Select * from table1 Where user='"
         +user+"' and password='"+pass+"'"                                                    + ""; 
          try
          { rs=st.executeQuery(sql);  
            int count=0;
            while (rs.next())
            { count++;} 
          if (count==0)                      OptionPane.showMessageDialog(null,"Access denied","Login  Fail",3);                                                                                                       
           }catch(Exception ex) {}                                              
          }                                      
                     );       
}
}

Java 學習筆記~2維陣列變數


class Data
{
    // 宣告x為2維陣列
    private  static int x[][]=new int[2][];
    private static double  w[]=new double [2];
    public static void setX(int[][] aX) { x = aX; }
    public static int[][] getX() {  return x;    }   
    public static double[] getW() {return w; }
    public static void setW(double[] aW) {w = aW;   }   
   
}
public class preceptron {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         //x 為一4x2 陣列
        int x[][]={{0,0},{0,1},{1,0},{1,1}};    
        double w[][]={{0.5,0.5}};      
        int i,j;       
        Data.setX(x);
        for (i=0;i<4;i++)
        {
             for (j=0;j<2;j++)  
                 System.out.print(Data.getX()[i][j]);
                 System.out.println();
        }

   /* Data.setW(w[0]);
    for (j=0;j<2;j++)
    System.out.println(Data.getW()[j]);    */
    }

}

Delphi 學習筆記偵測檔案夾的檔案個數


如何偵測檔案夾的檔案個數

function FileCount(filePath:string):integer;
var pathstr:string;
    sr: TSearchRec;
    FileAttrs: Integer;
begin
    pathstr:=GetCurrentDir;
    pathstr:=pathstr+'\sqlFile\*.*';
    Form1.Edit1.Text:=pathstr;
    FileAttrs := FileAttrs + faAnyFile;
    FileCount:=0;
    // FindFirst returns 0 if a file was successfully located, otherwise, it returns an //error code.

    if SysUtils.FindFirst('K:\torch\sqlFile\*.*', FileAttrs, sr) = 0 then
    begin
            with Form1.stringgrid1 do
            begin
                rowCount:=1;
                repeat
                if (sr.Attr and FileAttrs) = sr.Attr then
                begin
                   RowCount := RowCount + 1;
                   Cells[1,RowCount-1] := sr.Name;
                   Cells[2,RowCount-1] := IntToStr(sr.Size);
                   inc(FileCount);
                end;
//FindNext returns the next entry that matches the name and attributes specified in a //previous call to FindFirst. The search record must be one that was passed to FindFirst. //The return value is zero if the function was successful. Otherwise the return value is an //error code.            
    until FindNext(sr) <> 0;
            end;
    end;
end;

Delphi 學習筆記 指標


『@』是一個運算子,放在變數前面,傳回該變數再記憶體所在之位置。@也可以傳回程序或函數的記憶體位置。『^』有兩種用法,放在型態前面表示要宣告一個指標變數。放在指標變數後面,則為一個運算子,會傳回指標變數所紀錄的記憶體位置的資料值。


ex:

var x,y:Integer;
    p:^Integer;
begin
    x:=17 ;
    p:=@x;
    y:=p^;    showmessage(inttostr(y));
end;

type PInteger=^Integer; //宣告指標形態
var R:Real;
    I:Integer;
    P:Pointer;          //宣告通用型指標變數
    PI:PInteger;
begin

    P:=@R;             //任何型態變數均可指派記憶體位置給p
    PI=Pinteger(P);    //轉換通用型態指標P為整數指標
    I:=PI^;
end;


Pointer型態為通用型態指標,因為指定任何型態資料的記憶體位址,可以利用多用途的指標型態進行強制的資料型態轉換


程序型態允許開發人員以處理變數數值的方式來處理程序和函數

function Max(x,y:Integer):Integer;
begin
    if x>y then result:=x
    else result:=y;

procedure TForm1.Button3Click(Sender: TObject);
var F:function(x,y:Integer):Integer;
begin
   F:=Max; //可以將函數Max 指定給F
   showmessage(inttostr(F(3,5)));
end;end;

共用資料Shared Preferences

共用資料類別是用來處理基本型別的key-value 成對名稱與資料,該類別建構的物件可以存放Int、float、boolean 及字串型別


取得SharedPreferences類別的方式有:
getSharedPreferences(String name,int mode); 呼叫該方法需傳入兩個參數;第一個參數為自訂的儲存資料檔案名稱,如果指定的檔案不存在,則會在實際進行存取動作時自動建立。第二個參數為指定的操作模式
MODE_PRIVATE 只有呼叫的應用程式可以存取
MODE_WORLD_READABLE(1):允許其他應用程式可以讀取已經建立的檔案
MODE_WORLD_WRITABLE(2):允許其他應用程式可以寫入已經建立的檔案
最後呼叫COMMIT() 方法將資料存放


main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".Main" >

<RelativeLayout
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" >

  <Button
      android:id="@+id/write"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="write"
      />
  <Button
      android:id="@+id/read"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_toRightOf="@id/write"
  android:text="read"
      />   
  </RelativeLayout>
  
   <TextView
       android:id="@+id/tv"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"  
       />

</LinearLayout>





Main.java
package com.example.myiotest1;

import java.io.File;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

private Button write,read;
private TextView tv;
private  SharedPreferences sp;
private  SharedPreferences.Editor editor;
private File sdroot,approot,newfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
write=(Button)findViewById(R.id.write);
read=(Button)findViewById(R.id.read);
tv=(TextView)findViewById(R.id.tv);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();
editor.putString("user", "Jacky");
editor.putBoolean("Sound", true);
editor.putInt("Stage", 3);
editor.commit();
}
});

read.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();

tv.append(" "+sp.getInt("stage", 0));
tv.append(sp.getBoolean("Sound", true)?"true":"false");
tv.append(sp.getString("user", "who") );

}
});


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}