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網路程式設計 第三版(歐萊禮出版) 第六章範例