1.Colloection 延續
Set:無次序、無重複
List:有次序、有重複
2.測試 ArrayList & LinkedList
TestArrayList.java
import java.util.*;
public class TestArrayList {
public static void main(String[] args) {
ArrayList al = new ArrayList();
long i = 0;
Calendar c1 = Calendar.getInstance();
System.out.println("開始時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
while ( al.size() <= 1000000) {
i ++;
al.add(0, new Long(i));
}
c1 = Calendar.getInstance();
System.out.println("結束時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
/*
Iterator it = al.iterator();
while ( it.hasNext() ) {
System.out.print( it.next() + ", ");
}
*/
c1 = Calendar.getInstance();
System.out.println("開始時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
System.out.println(" 1 的位置在 " + al.indexOf(new Long((long)1)) );
c1 = Calendar.getInstance();
System.out.println("結束時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
}
}
TestLinkedList.java
import java.util.*;
public class TestLinkedList {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
long i = 0;
Calendar c1 = Calendar.getInstance();
System.out.println("開始時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
while ( ll.size() <= 1000000) {
i ++;
ll.add(0, new Long(i));
}
c1 = Calendar.getInstance();
System.out.println("結束時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
/*
Iterator it = ll.iterator();
while ( it.hasNext() ) {
System.out.print( it.next() + ", ");
}
*/
c1 = Calendar.getInstance();
System.out.println("開始時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
System.out.println(" 1 的位置在 " + ll.indexOf(new Long((long)1)) );
c1 = Calendar.getInstance();
System.out.println("結束時間 " + c1.get(Calendar.MINUTE) + " : "
+ c1.get(Calendar.SECOND));
}
}
結論:測試是將新的插入到已存在的陣列的第一個。所以 ArrayList 較慢。
3.雜湊碼
HashMapEx.java
import java.util.*;
class HashMapEx {
public static void main(String [] args) {
HashMap map = new HashMap(); //建立HashMap物件
map.put("我最喜歡的零食", "冰淇淋");
map.put("我最喜歡的寵物", "貓");
map.put("我最喜歡的電影", "哈利波特");
map.put("我最喜歡的零食", "巧克力");
map.put("我最喜歡的書籍", "哈利波特");
Set set = map.keySet();
System.out.println( set ); //直接將set列出來
Iterator iterator = set.iterator(); //取得重複器
while(iterator.hasNext()) {
System.out.print(" "+ map.get(iterator.next()) +" ");
}
System.out.println();
Collection collection = map.values();
System.out.println( collection ); //直接將collection列出來
System.out.println( map ); //直接將map列出來
System.out.println( map.get("我最喜歡的寵物") );
}
}
4.equals
Motocycle.java
public class Motocycle {
double cc =50.0;
String co;
String color;
Motocycle(double cc, String co, String color){
this.cc =cc;
this.co =co;
this.color =color;
}
public void showDetail(){
System.out.println(
co +"牌, "
+color +" 色, "
+cc +"cc, 摩托車."
);
}
public boolean equals(Object obj){
boolean isSame =false;
if (
obj !=null
&& obj instanceof Motocycle
){
Motocycle m = (Motocycle)obj;
if (
m.cc == cc
&& m.co.equals(co)
&& m.color.equals(color)
){
isSame =true;
}
}
return isSame;
}
public int hashCode(){
return ((int)cc);
}
/*
@Override
public String toString(){
return "作者: 吳老獅";
}
*/
}
Test.java
import java.util.*;
public class Test {
public static void main ( String[] args ){
Motocycle m01 = new Motocycle(100.0, "山葉", "金");
m01.showDetail();
Motocycle m02 = new Motocycle(100.0, "山葉", "金");
m02.showDetail();
System.out.println("m01.equals(m02) ? " +m01.equals(m02) );
System.out.println(m01);
System.out.println("m01.hashCode() ? " +Integer.toHexString(m01.hashCode()) );
System.out.println(m02);
System.out.println("m02.hashCode() ? " +Integer.toHexString(m02.hashCode()) );
}
}
5.Switch ~ Case
test.java
import java.util.*;
public class Test {
public static void main ( String[] args ){
Scanner s = new Scanner( System.in );
System.out.print("請輸入欲購買的車種: 0.不買; 1.國民車; 2.中級車; 3.高級車; ->");
int i = s.nextInt();
System.out.print("贈品有");
switch (i) {
default:
case 3:
System.out.print(", 安全氣囊");
case 2:
System.out.print(", 隔熱貼紙 + 隔音設備");
case 1:
System.out.print(", 汽車椅套");
case 0:
System.out.print(", 賞車來店禮");
}
}
}
6.大樂透開獎 (for 迴圈 + if 判斷式 )
Test.java
public class Test {
public static void main ( String[] args ){
int[] ball = new int[7];
//取得樂透彩號碼
for ( int i=0; i<ball.length; i++){
ball[i] =(int)(Math.random()*49+1);
//檢查是否重複
for ( int j=0; j<i; j++){
if ( ball[i] == ball[j] ){
i--;
break;
}
}
}
//顯示樂透彩號碼
for ( int i=0; i<ball.length; i++){
System.out.print( ball[i] +", ");
}
}//main
}//class
7.多維陣列
Test,java
public class Test {
public static void main ( String[] args ){
/* ok
String [] MarryPets = new String [] { "Marry's Cat", "Marry's Dog" };
*/
String [] MarryPets;
MarryPets = new String [] { "Marry's Cat", "Marry's Dog" };
/* compile err
String [] JoePets;
JoePets = { "Joe's Fish", "Joe's Bird", "Joe's Dog"};
*/
String [] JoePets = { "Joe's Fish", "Joe's Bird", "Joe's Dog"};
String [] LindaPets = { "Linda's Horse" };
String [][] myFriendPets = { MarryPets, JoePets, LindaPets };
for (int i=0; i < myFriendPets.length; i++){
for (int j=0; j< myFriendPets[i].length; j++){
System.out.println("myFriendPets[" + i + "][" + j + "] = " + myFriendPets[i][j]);
}
}
}
}
8.樂透 -- Set
利用 set 不重複的特性來取樂透號碼
SortedLottary.java
import java.util.*;
public class SortedLottary {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
Integer ball = null;
do {
ball = new Integer( (int)(Math.random()*49+1) );
System.out.print( ball + ", ");
ts.add( ball );
} while ( ts.size() < 7 );
/*
Iterator it = ts.iterator();
while ( it.hasNext() ) {
System.out.print(it.next() + ", ");
}
*/
System.out.println("\n樂透彩: " + ts);
for( Object i : ts ){
System.out.print((Integer)i + ", ");
}
}
}
9.String Number
列出二數字相加,若前面有字串,則二數字會被當成字串相加。若字串在最後面就沒影響。
範例:
Test.java
public class Test {
public static void main ( String[] args ){
int salary = 18000;
int bonus = 2000;
System.out.println("工讀生甲: ");
System.out.println("\t 本月基本薪資: " + salary);
System.out.println("\t 本月獎金: " + bonus);
/* 老板會殺了你
System.out.println("\t 本月實領薪資: " + salary + bonus);
*/
System.out.println("\t 本月實領薪資: " + (salary + bonus) );
System.out.println( salary +bonus +" 元整");
}
}
10.String trap
== 與 equals
在JAVA裡, == 是比較二個物件所指向的記憶體位置是否為同一個。
equals,是比較二個物件所代表的內容是否相同。
代表的內容:有以下四種,除此之外, equals 就是 == 的意思。
java.lang.String
java.io.File
java.net.URL
java.util.Date
範例:
Test.java
public class Test{
public static void main ( String[] args ){
String yn01 = "yes";
String yn02 = "yes";
String yn03 = new String("yes");
System.out.println("yn01 = " + yn01);
System.out.println("yn02 = " + yn02);
System.out.println("yn03 = " + yn03);
System.out.println(" yn01 == yn02 結果: " + ( yn01 == yn02 ) );
System.out.println(" yn01 == yn03 結果: " + ( yn01 == yn03 ) );
System.out.println(" yn01.equals(yn03) 結果: " + yn01.equals(yn03) );
}
}
11.Find Vitamin
在檔案中尋找特定字串的資料,並寫到新檔案
範例:
FindVitamin.java
import java.io.*;
public class FindVitamin{
public static void main( String[] args){
try{
FileReader input = new FileReader( args[0] );
BufferedReader bufInput = new BufferedReader( input );
try{
FileWriter output = new FileWriter( args[1] );
BufferedWriter bufOutput = new BufferedWriter( output );
try{
String line;
//read the first & second line因為第一、二行為表頭,不必尋找
line = bufInput.readLine();
bufOutput.write( line, 0, line.length() );
bufOutput.newLine();
line = bufInput.readLine();
bufOutput.write( line, 0, line.length() );
bufOutput.newLine();
line = bufInput.readLine();
while( line != null){
//轉成大寫後,找到 VITAMIN 的位置是第幾位,0代表第一位
if( line.toUpperCase().indexOf("VITAMIN") >= 0){
//write the line out to the output file
bufOutput.write( line, 0, line.length() ); //從第一位置 (0)開始寫,寫到該行的長度為止。
bufOutput.newLine(); //在output檔案中開啟下一行
}
//read the next line
line = bufInput.readLine(); //在input檔案中讀取下一行
}
} finally {
bufOutput.close();
}
} finally {
bufInput.close();
}
} catch( Exception e){
e.printStackTrace();
}
}
}
12擷取部分字串
Test.java
public class Test {
public static void main ( String[] args ){
String id = "A123456789";
// StringBuffer id = new StringBuffer("A123456789");
// StringBuilder id = new StringBuilder("A123456789");
System.out.println("身分證號碼: " +id);
System.out.println("開頭字母為: " +id.substring(0,1) ); //從0的位置開始找到第1的位置
System.out.println("數字部分為: " +id.substring(1) ); //從1的位置開始找到最後
System.out.println("檢查碼: " +id.substring( id.length()-1 ) ); //從字串長度減一,即最後一個
}
}
13.replace method (StringBuffer & StringBuilder)
Test.java
public class Test {
public static void main ( String[] args ){
StringBuffer address = new StringBuffer("地址:台北縣三重市大同路");
// StringBuilder address = new StringBuilder("地址:台北縣三重市大同路");
System.out.println("地址更名前 --> " +address);
System.out.println("地址更名後 --> " +address.replace(3,6,"新北市") );
address.replace(8,9,"區");
System.out.println(address);
}
}
PS:StringBuffer VS StringBuilder
在Java中常用到字串的處理,
但String本身是固定長度不能改變內容的,
我們常用+來連結附加字串其實相當耗費資源,
在大量處理字串的情況下我們有更好的選擇。
Java在J2SE5.0之後提供了StringBuilder類別,
他有許多好用的操作字串的方法如:
insert()、reverse()、replace()、append()等,
更多詳細的API可見:java.lang.StringBuilder 的API說明。
而很多人會有這樣的疑問(我也是一直弄不清楚才來寫這篇的XD),
StringBuilder和StringBuffer有什麼差別呢?
他們兩個提供了相同的介面,
然而在不需考量多執行緒同步的時候我們使用StringBuilder來獲得最佳的效率,
要考慮多執行緒的情況下使用StringBuffer來讓類別自動處理同步的問題。
另外這兩個類別雖然相當好用,
但似乎許多人都會找不到如何清空他,
這大概是因為單純看 method 時沒有看到叫做 clear() 之類的 method,
但其實我們還是可以透過 delete(int start, int end) 這個 method 來達成目的。
用法就像這樣:stringBuffer.delete(0, stringBuffer.length());
14.replace method -2 (String)
test.java
public class Test {
public static void main ( String[] args ){
String guestBook = "<a href=\'winjow.net\'> 吳老獅 </a>";
System.out.println("留言板內容 --> " +guestBook);
// System.out.println( guestBook.replace('<','<') );
guestBook = guestBook.replace('<','<');
System.out.println("留言板內容 --> " +guestBook);
guestBook = guestBook.replace('>','>');
System.out.println("留言板內容 --> " +guestBook);
}
}
結論 for 13 & 14 :
不需要改字串內容時用 string
需要改字串內容,不需考慮多執行緒同步時用 StringBuilder
需要改字串內容,也需考慮多執行緒同步時用 StringBuffer
15.判斷身分證真假 (substring_Wrapper)
1.身分證公式參考維基百科
Test.java
import java.util.*;
public class Test {
public static void main ( String[] args ){
//開頭字母與數字的對應, 陣列[0]代表A
int[] first_alphabet = {
10,11,12,13,14,15,16,17,34,18,19,20,21,
22,35,23,24,25,26,27,28,29,32,30,31,33
};
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] id_array =null;
Scanner s = new Scanner(System.in);
//讓使用者輸入身分證字號
System.out.print("請輸入身分證字號(含英文字母共十個字): ");
String keyin = s.next();
keyin = keyin.trim().toUpperCase(); //防止頭尾不小心空白
//身分證號碼字數是否正確
String first_letter = keyin.substring(0,1);
int checkNumber=0; //運算用,事後查看除以10餘數是否為零.
if ( (keyin !=null)
&& (keyin.length() ==10)
&& (letters.indexOf( first_letter ) >=0 )
){
id_array = keyin.toCharArray();
//演算出檢查碼, 與使用者輸入的身分證末尾碼是否相符
char c = keyin.charAt(0);
checkNumber = first_alphabet[ c-65 ] /10; //A:ASCII=65
checkNumber = checkNumber + first_alphabet[c-65] %10 *9;
for ( int i=1; i<id_array.length-1; i++){
if ( id_array[i] >=48 && id_array[i] <=57 ){ //0:ASCII=48,9:ASCII=57
checkNumber += ( id_array[i]-48 ) * (9-i);
} else {
System.out.println("發現第 " +(i+1) +" 個字非數字: " +id_array[i]);
System.exit(0);
}
}
checkNumber += ( id_array[9]-48 )*1;
// ?左邊是布林判斷式,True就執行?與 :之間,faulse就 : 後面
System.out.println( checkNumber%10==0?"正確":"作假");
} else {
System.out.println("輸入有誤!");
}
} //main
} //class
PS:ASCII 對照圖
No comments:
Post a Comment