2012年12月12日 星期三

Java Sagit's 計分程式

題目:Sagit's 計分程式


import java.util.Scanner;

public class Sagits{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
  
        while(sc.hasNext()){
            int number = sc.nextInt();
   
            System.out.println(
                (number > 40) ? 100 : 
                (number > 20) ? 100 - (40 - number) :
                (number > 10) ? 80 - (20 - number) * 2 :
                number * 6
            );
        }
    }
}

Java 空間切割

題目:空間切割

公式: N*(N*N+5)/6+1


import java.util.Scanner;
public class A044 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            System.out.println(n*(n*n+5)/6+1);
        }
    }
}

Java 平面圓形切割

題目:平面圓形切割

公式: N*N-N+2


import java.util.Scanner;
public class A042 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            System.out.println(n*n -n+2);
        }
    }
}

Java 五則運算

題目:五則運算


參考 中序式轉後序式 後序式運算


注意:此程式用Java SE7去寫,如果是用SE6以下去編譯,switch部分會編譯錯誤


import java.util.*;

public class FiveOperations{
    public static int priority(String str){
        switch( str ){
            case "+": case "-": 
                return 1;
            case "*": case"/": case "%": 
                return 2;
            default: 
                return 0;
        }
    }
 
    public static int count(String op, int a, int b){
        switch( op ){
            case "+": return a + b;
            case "-": return a - b;
            case "*": return a * b;
            case "/": return a / b;
            case "%": return a % b;
            default: throw new ArithmeticException(op + " not defined");
        }
    }

    public static String toPostfix(String str){
        StringBuffer sb = new StringBuffer();
        LinkedList<String> stack = new LinkedList<String>();
        for(String sub : str.split(" ") ){
            if("(".indexOf(sub) != -1){
                stack.add(sub);
            }else if("+-*/%".indexOf(sub) != -1){
                while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
                    sb.append(stack.removeLast() + " ");
                }
                stack.add(sub);
            }else if(")".indexOf(sub) != -1){
                while( "(".indexOf(stack.getLast()) == -1 ){
                    sb.append(stack.removeLast() + " ");
                }
                stack.removeLast();
            }else{
                sb.append(sub + " ");
            }
        }
  
        while(!stack.isEmpty()){ sb.append(stack.removeLast() + " "); }
        return sb.toString();
    }
 
    public static int answer(String str){
        Stack<Integer> stack = new Stack<Integer>();
        for(String sub : toPostfix(str).split(" ")){
            if("+-*/%".indexOf(sub) != -1){
                int b = stack.pop();
                int a = stack.pop();
                stack.push(count(sub, a, b));
            }else{
                stack.push(Integer.parseInt(String.valueOf(sub)));
            }
        }
        return stack.pop();
    }
 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            System.out.println( answer(str) );
        }
    }
}

2012年12月11日 星期二

取得Socket資訊

在命令列輸入一串主機名稱,並嘗試對各個主機開啟一個Socket
印出遠端主機、遠端通訊埠、本地位址及本地通訊埠

import java.net.*;
import java.io.*;

public class SocketInfo{
    public static void main(String[] args){
        for(int i = 0; i < args.length; i++){
            try{
                Socket s = new Socket(args[i], 80);
                System.out.println("Connected to " + s.getInetAddress()
                    + "on port " + s.getPort() + " from port "
                    + s.getLocalPort() + " of "
                    + s.getLocalAddress());
            }
            catch(UnknownHostException ex){
                System.err.println("I can't find " + args[i]);
            }
            catch(SocketException ex){
                System.err.println("Could not connect to " + args[i]);
            }
            catch(IOException ex){
                System.err.println(ex);
            }
        }//for end
    }//main end
}//SocketInfo end


參考資料:Java網路程式設計 第三版(歐萊禮出版) 第九章範例

下載網頁

在命令列輸入指定的URL,印出URL的原始資料
如果URL指向一個HTML檔案,則印出HTML的原始內容

import java.net.*;
import java.io.*;

public class DownloadHTML{
    public static void main(String[] args){
        if( args.length > 0 ){
            try{
                URL url = new URL(args[0]);
                InputStream in = url.openStream();
                in = new BufferedInputStream(in);
   
                Reader r = new InputStreamReader(in);
                int c;
                while((c = r.read()) != -1){
                    System.out.print((char) c);
                }
            }
            catch(MalformedURLException ex){
                System.out.println(args[0] + " is not a parseable URL");
            }
            catch(IOException ex){
                System.out.println(ex);
            }
        }//if end
    }//main end
}//DownloadHTML end


參考資料:Java網路程式設計 第三版(歐萊禮出版) 第七章範例

簡易nslookup

在命令列輸入主機名稱,印出IP位址
輸入IP位址,印出主機名稱

import java.net.*;
import java.io.*;

public class NsLookUp{
    public static void main(String[] args){
        if(args.length > 0){
            for(int i = 0; i < args.length; i++){
                System.out.println(lookup(args[i]));
            }
        }
    }
 
    public static String lookup(String host){
        InetAddress address;
  
        try{
            address = InetAddress.getByName(host);
        }
        catch(UnknownHostException ex){
            return "Cannot find" + host;
        }
  
        if(isHostName(host)){//host name
            return address.getHostAddress();
        }
        else{ //IP address
            return address.getHostName();
        }
    }
 
    public static boolean isHostName(String host){
        //IPv6
        if(host.indexOf(':') != -1) return false;
  
        char[] ch = host.toCharArray();
        for(int i = 0; i < ch.length; i++){
            if(!Character.isDigit(ch[i])){
                //host name
                if(ch[i] != '.') return true;
            }
        }
  
        //不是host name就是IP
        return false;
    }
}


參考資料:Java網路程式設計 第三版(歐萊禮出版) 第六章範例

2012年5月19日 星期六

Java 中序式轉後序式


import java.util.*;

public class Postfix{
    public static int priority(String str){
        switch( str ){
            case "+": case "-": 
                return 1;
            case "*": case"/": case "%": 
                return 2;
            default: 
                return 0;
        }
    }

    public static String toPostfix(String str){
        StringBuffer sb = new StringBuffer();
        LinkedList<String> stack = new LinkedList<String>();
        for(String sub : str.split(" ") ){
            if("(".indexOf(sub) != -1){
                stack.add(sub);
            }else if("+-*/%".indexOf(sub) != -1){
                while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
                    sb.append(stack.removeLast() + " ");
                }
                stack.add(sub);
            }else if(")".indexOf(sub) != -1){
                while( "(".indexOf(stack.getLast()) == -1 ){
                    sb.append(stack.removeLast() + " ");
                }
                stack.removeLast();
            }else{
                sb.append(sub + " ");
            }
        }
  
        while(!stack.isEmpty()){ sb.append(stack.removeLast()); }
        return sb.toString();
    }
 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            System.out.println( toPostfix(str) );
        }
    }
}

參考:良葛格學習筆記

2012年5月13日 星期日

Java 大數運算


import java.util.*;
import java.math.*;

public class BigNumberCount{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            StringBuffer sb = new StringBuffer(str);
   
            String str1 = sb.substring(0, sb.indexOf(" "));
            sb.delete(0, sb.indexOf(" ")+1);
            String symbol = sb.substring(0, sb.indexOf(" "));
            String str2 = sb.substring(sb.indexOf(" ")+1, sb.length());
            
            BigInteger a = new BigInteger(str1);
            BigInteger b = new BigInteger(str2);
   
            switch( symbol.charAt(0) ){
                case '+':
                    System.out.println( a.add(b) );
                    break;
                case '-':
                    System.out.println( a.subtract(b) );
                    break;
                case '*':
                    System.out.println( a.multiply(b) );
                    break;
                case '/':
                    System.out.println( a.divide(b) );
                    break;
            }  
        }
    }
}

說明

直接使用Java.math底下的BigInteger類別實做

題目

大數運算

參考

超長整數運算(大數運算)

2012年4月13日 星期五

Java 迴文


import java.util.Scanner;

public class Palindrome{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                String str;
  
                while( sc.hasNext() ){
                        str = sc.nextLine();
   
                        String tmp = "";
                        int length = str.length() - 1;
                        for(int i = length; i >= 0; i--){
                                tmp += str.charAt(i);
                        }
   
                        if( str.equals(tmp) ){
                                System.out.println("yes");
                        }
                        else{
                                System.out.println("no");
                        }
                }
        }
}

題目
參考程式

2012年4月12日 星期四

Java 阿姆斯壯數


import java.util.Scanner;

public class ArmstrongNumber{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                int a,b;
  
                while( sc.hasNext() ){
                        a = sc.nextInt();
                        b = sc.nextInt();
                        int count = 0;
   
                        for(int i = a; i <= b; i++){
                                boolean ans = false;
                                int length = String.valueOf(i).length();
                                int sum = 0;
                                switch( length ){
                                        case 7:
                                                sum += Math.pow(i/1000000,length);
                                        case 6:
                                                sum += Math.pow((i%1000000)/100000,length);
                                        case 5:
                                                sum += Math.pow((i%100000)/10000,length);
                                        case 4:
                                                sum += Math.pow((i%10000)/1000,length);
                                        case 3:
                                                sum += Math.pow((i%1000)/100,length);
                                        case 2:
                                                sum += Math.pow((i%100)/10,length);
                                        case 1:
                                                sum += Math.pow(i%10,length);
                                                break;
                                }
    
                                if( sum == i ){
                                        System.out.print( i + " ");
                                        count++;
                                }
                        }
   
                        if( count != 0 ){
                                System.out.println();
                        }
                        else{
                                System.out.println("none");
                        }
   
                }
        } 
}


題目

Java 數字翻轉


import java.util.Scanner;

public class NumberTurn{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                String str;
  
                while( sc.hasNext() ){
                        str = sc.nextLine();
   
                        char c [] = str.toCharArray();
                        String tmp = "";
   
                        for( int i = c.length - 1; i >= 0; i-- ){
                                tmp += c[i];
                        }
   
                        System.out.println( Integer.parseInt(tmp) );
                }
        }
}

題目
參考程式

Java 二進位轉換


import java.util.Scanner;

public class CarryTransform{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                int num;
  
                while( sc.hasNext() ){
                        num = sc.nextInt();
   
                        System.out.println( Integer.toBinaryString(num) );
                }
        }
}

題目

Java 最大公因數


import java.util.Scanner;

public class GCD{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                int a,b;
  
                while( sc.hasNext() ){
                        a = sc.nextInt();
                        b = sc.nextInt();
   
                        int i = 0;
   
                        while( b != 0 ){
                                i = a % b;
                                a = b;
                                b = i;
                        }
   
                        System.out.println( a );
                }
        }
}

題目

2012年4月9日 星期一

Java 身分證檢驗


import java.util.Scanner;

public class IdAuthentication{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                String str;
  
                while( sc.hasNext() ){
                        str = sc.nextLine();
                        char c [] = str.toCharArray();
   
                        if( c[0] == 88 || c[0] == 89 ){
                                c[0] -= 58;
                        }
                        else if( c[0] >= 65 && c[0] <= 72 ){
                                c[0] -= 55;
                        }else if( c[0] >= 74 && c[0] <= 78){
                                c[0] -= 56;
                        }else if( c[0] >= 80 && c[0] <= 86){
                                c[0] -= 57;
                        }else{
                                c[0] = (c[0] == 73) ? 34 : (c[0] == 79) ? 35 : 
                                        (c[0] == 87) ? 32 : (c[0] == 90) ? 33 : c[0];
                        }
   
                        int sum = c[0]/10 + (c[0]%10)*9 + (c[9]-48);
   
                        for(int i = 1; i < c.length-1; i++){
                                sum += (c[i]-48)*(9-i);
                        }
   
                        if( sum % 10 == 0 ){
                                System.out.println("real");
                        }
                        else{
                                System.out.println("fake");
                        }
                }
        }
}


題目

2012年4月6日 星期五

Java 數獨判斷


import java.util.Scanner;

public class Sudoku{
    public static int array [][] = new int [9][9];
 
    public static boolean checkRow(int row){
        int sum = 0;
  
        for(int i = 0; i < array.length; i++){
            sum += array[row][i];
        }
  
        if( sum < 45 || sum > 45 ){
            return false;
        }
  
        return true;
    }
 
    public static boolean checkColumn(int column){
        int sum = 0;
  
        for(int i = 0; i < array.length; i++){
            sum += array[i][column];
        }
  
        if( sum < 45 || sum > 45 ){
            return false;
        }
  
        return true;
     }
 
     public static boolean checkLittlePalaceGrid(int box){
         int sum = 0;
         int row = (box / 3) * 3;
         int column = (box < 3) ? box*3 : (box < 6) ? (box - 3)*3 : (box - 6)*3;
  
         for(int i = 0; i < 3; i++){
             for(int j = 0; j < 3; j++){
                 sum += array[i + row][j + column];
             }
         }
  
         if( sum < 45 || sum > 45 ){
             return false;
         }
         return true;
     }

     public static void main(String[] args){
         Scanner sc = new Scanner(System.in);
         boolean row=true,column=true,lpg=true;
  
         while( sc.hasNext() ){
             for(int j = 0; j < 9; j++ ){
                 int a [] = {0,0,0,0,0,0,0,0,0};
                 for(int k = 0; k < 9; k++){
                     a[k] = sc.nextInt();
                 }
                 array[j] = a;
              }
   
              int i = 0;
              while(i < array.length){
                  row = checkRow(i);
                  column = checkColumn(i);
                  lpg = checkLittlePalaceGrid(i);
                  if(row == false || column == false || lpg == false){
                      System.out.println("no");
                      break;
                  }
   
                  if( i == array.length - 1 ){
                      System.out.println("yes");
                  }
                  i++;
              }
         }  
     }
}

題目

2012年4月4日 星期三

Java 矩陣翻轉


import java.util.Scanner;

public class Matrix{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
                int row,colum;
                int matrix [][];
  
                while(sc.hasNext()){
                        row = sc.nextInt();
                        colum = sc.nextInt();
                        matrix = new int [row][colum];
   
                        for( int i = 0; i < row; i++ ){
                                for( int j = 0; j < colum; j++){
                                        matrix[i][j] = sc.nextInt();
                                }
                        }

                        for( int i = 0; i < colum; i++ ){
                                for( int j = 0; j < row; j++){
                                        System.out.print(matrix[j][i] + " ");
                                }
                                System.out.println();
                        }
                }
        }
}

題目

2012年3月19日 星期一

Eclipse無法Debug

最近又開始玩android

當要debug的時候竟然出現錯誤

訊息"Error generating final archive: Debug Certificate expired on....."

原因不明,所以就google一下

原來是憑證到期了

解法如下:

第一步: 把"C:\Documents and Settings\user\.android"裡的debug.keystore檔刪除

第二步: 點開時間與日期內容,選時區

第三步: 更新時間,後按確定

第四步: 在eclipse重新建一個專案

第五步: 直接debug讓它重新建置 debug.keystore檔

這樣就OK囉!


參考文章

2012年3月5日 星期一

Java 羅馬數字


import java.util.*;

public class RomeNumber{
        public static void main(String[] args){
                Scanner sc = new Scanner(System.in);
  
                while(sc.hasNext()){
                        String str [] = sc.nextLine().split(" ");
                        if(str[0].equals("#")){
                                break;
                        }

                        int a = transformIntNumber(str[0]);
                        int b = transformIntNumber(str[1]);
                        int sum = Math.abs(a - b);

                        if( sum == 0){
                                System.out.println("ZERO");
                        }
                        else{
                                System.out.println(transformRomeNumber(sum));
                        }
                }
        } 

        public static int transformIntNumber(String s){
                int count = 0;
                int a [] = new int [s.length()];
                for(int i = 0; i < a.length; i++){
                        switch(s.charAt(i)){
                                case 'I':
                                        a[i] = 1;
                                        break;
                                case 'V':
                                        a[i] = 5;
                                        break;
                                case 'X':
                                        a[i] = 10;
                                        break;
                                case 'L':
                                        a[i] = 50;
                                        break;
                                case 'C':
                                        a[i] = 100;
                                        break;
                                case 'D':
                                        a[i] = 500;
                                        break;
                                case 'M':
                                        a[i] = 1000;
                                        break;
                        }
                }
  
                for(int i = 0; i < a.length; i++){
                        if( i == (a.length - 1)){
                                count += a[i];
                                break;
                        }
                        else if( a[i] < a[i+1] ){
                                count -= a[i];
                        }
                        else{
                                count += a[i];
                        }
                }
  
                return count;
        }

        public static String transformRomeNumber(int a){
                String str = "";
                int index;
                String rome [] = {"I","V","X","L","C","D","M"};
                int num [] = {1,5,10,50,100,500,1000};
                Arrays.sort(num);

                while( a > 0 ){
                        index = Arrays.binarySearch(num, a);
                        if(index == -8){
                                index = 6;
                        }else if(index < 0){
                                index = -1 * index -2;
                                int i = index / 2 * 2;
                                if(a + num[i] >= num[index + 1]){
                                        str += rome[i];
                                        a += num[i];
                                        index++;
                                }
                        }
                        str += rome[index];
                        a -= num[index];
                }
  
                return str;
        }
}

題目
參考程式