/*
 *  Filename: testStringReverse.cs
 *
 *  Compile: csc testStringReverse.cs
 *  Execute: testStringReverse
 */

using System;

public class StringReverseApp {
    public static void Main(string[] args) {
        string a, b;
        a = "Hello, world!";
        b = "안녕하세요?";
        char[] arr = a.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine(new String(arr));
        arr = b.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine(new String(arr));
    }
}
/*
Expected result:
!dlrow ,olleH
?요세하녕안
*/





Creative Commons License 
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은 초등학교에서 배우는 나눗셈 계산표를 만들어주는 Java 소스 코드이다.
나눗셈 계산표를 완성하고 나서 약수, 배수 관계를 알려준다.


  1. /*
  2.  *  Filename: MakeDivisionTableApp.java
  3.  *
  4.  *  Purpose:  Make a division table in a handy written form.
  5.  *
  6.  *  Compile: javac -d . MakeDivisionTableApp.java
  7.  *
  8.  *  Execute: java MakeDivisionTableApp 12345 32
  9.  *           java MakeDivisionTableApp 500210 61
  10.  *
  11.  *     Date:  2008/05/15
  12.  *   Author:  PH Kim   [ pkim ((AT)) scripts.pe.kr ]
  13.  */
  14. import java.math.*;
  15. public class MakeDivisionTableApp {
  16.     public static void printUsage() {
  17.          // System.out.println("Using: java MakeDivisionTableApp [numerator] [denominator]");
  18.          // System.out.println("Make a division table in a handy written form.");
  19.          System.out.println("사용법: java MakeDivisionTableApp [피제수] [제수]");
  20.          System.out.println("손으로 작성한 형태의 나눗셈 표를 만들어준다.");
  21.     }
  22.     public static String simplify(double v) {
  23.         String t = "" + v;
  24.         if (t.endsWith(".0"))
  25.             t = t.substring(0, t.length() - 2);
  26.         return t;
  27.     }
  28.     public static String simplify(BigInteger v, int width) {
  29.         String t = "" + v;
  30.         if (t.endsWith(".0"))
  31.             t = t.substring(0, t.length() - 2);
  32.         int len = t.length();
  33.         if (len < width)
  34.             t = "                                                                                             ".substring(0, width - len) + t;
  35.         return t;
  36.     }
  37.     public String getSuffix(BigInteger v) {
  38.         BigInteger t = v.mod(new BigInteger("10"));
  39.         String suffix = "은";
  40.         if ("2459".indexOf("" + t) >= 0) {
  41.             suffix = "는";
  42.         }
  43.         return suffix;
  44.     }
  45.     public BigInteger makeTable(BigInteger numer, BigInteger denom, BigInteger quotient) {
  46.         String strNumer = "" + numer;
  47.         String strDenom = "" + denom;
  48.         String strQuotient = "" + quotient;
  49.         int lenN = strNumer .length();
  50.         int lenD = strDenom .length();
  51.         int lenQ = strQuotient .length();
  52.         int offsetLeft = 3 + lenD + 3;
  53.         String spaces = "                                                                                 ";
  54.         String uline  = "_________________________________________________________________________________".substring(0, lenN + 2);
  55.         String sline  = "---------------------------------------------------------------------------------".substring(0, lenN);
  56.         int bias = lenN - lenQ;
  57.         System.out.println(spaces.substring(0, offsetLeft) + spaces.substring(0, bias) + quotient);
  58.         System.out.println(spaces.substring(0, offsetLeft - 2) + uline);
  59.         System.out.print("   " + strDenom + " ) " + strNumer);
  60.         String strTmpR = strNumer.substring(0, bias + 1);
  61.         BigInteger tmpR = new BigInteger(strTmpR);
  62.         BigInteger tmpSub = BigInteger.ZERO;
  63.         String oneDigit = null;
  64.         for (int i = 0; i < lenQ; i++) {
  65.             if (strQuotient.substring(i, i + 1).equals("0")) {
  66.                 if (i + 1 < lenQ) {
  67.                     oneDigit = strNumer.substring(bias + i + 1, bias + i + 2);
  68.                     System.out.print(oneDigit);
  69.                     strTmpR += oneDigit;
  70.                     tmpR = new BigInteger(strTmpR);
  71.                 }
  72.             }
  73.             else {
  74.                 System.out.println();
  75.                 tmpSub = new BigInteger(strQuotient.substring(i, i + 1)).multiply(denom);
  76.                 System.out.println(spaces.substring(0, offsetLeft) + simplify(tmpSub, bias + i + 1));
  77.                 System.out.println(spaces.substring(0, offsetLeft) + sline);
  78.                 tmpR = tmpR.subtract(tmpSub);
  79.                 if (tmpR.equals(BigInteger.ZERO) && i + 1 < lenQ) {
  80.                     System.out.print(spaces.substring(0, offsetLeft) + spaces.substring(0, bias + i + 1));
  81.                 }
  82.                 else {
  83.                     System.out.print(spaces.substring(0, offsetLeft) + simplify(tmpR, bias + i + 1));
  84.                 }
  85.                 strTmpR = "" + tmpR;
  86.                 if (i + 1 < lenQ) {
  87.                     oneDigit = strNumer.substring(bias + i + 1, bias + i + 2);
  88.                     System.out.print(oneDigit);
  89.                     strTmpR += oneDigit;
  90.                     tmpR = new BigInteger(strTmpR);
  91.                 }
  92.             }
  93.         }
  94.         System.out.println();
  95.         return tmpR;
  96.     }
  97.     public static void main(String[] args) {
  98.         if (args.length < 2) {
  99.             printUsage();
  100.             System.exit(1);
  101.         }
  102.         BigInteger a = null;
  103.         BigInteger b = null;
  104.         try {
  105.             a = new BigInteger(args[0]);
  106.             b = new BigInteger(args[1]);
  107.         }
  108.         catch (NumberFormatException ex) {
  109.             System.out.println("피제수: " + args[0] + ", 제수: " + args[1]);
  110.             System.out.println("숫자 입력에 오류가 있습니다.");
  111.             System.exit(1);
  112.         }
  113.         if (a.compareTo(BigInteger.ZERO) <= 0) {
  114.             System.out.println("피제수: " + a);
  115.             System.out.println("피제수는 양의 정수라야 합니다.");
  116.             System.exit(1);
  117.         }
  118.         else if (b.compareTo(BigInteger.ZERO) <=0) {
  119.             System.out.println("제수: " + b);
  120.             System.out.println("제수는 양의 정수라야 합니다.");
  121.             System.exit(1);
  122.         }
  123.         MakeDivisionTableApp app = new MakeDivisionTableApp();
  124.         BigInteger q = a.divide(b);
  125.         BigInteger r = a.mod(b);
  126.         System.out.print("나눗셈 " + a + " ÷ " + b + " 의 결과: ");
  127.         System.out.print("몫: " + q + ", ");
  128.         System.out.println("나머지: " + r);
  129.         System.out.println();
  130.         BigInteger k = app.makeTable(a, b, q);
  131.         if (k.equals(r)) {
  132.             System.out.println("\n나머지: " + k);
  133.         }
  134.         if (k.equals(BigInteger.ZERO)) {
  135.             System.out.println(a + " = " + b + " x " + q);
  136.             System.out.println(a + app.getSuffix(a) + " " + b + "의 배수(mupltiple)이다.");
  137.             System.out.println(b + app.getSuffix(b) + " " + a + "의 약수(divisor)이다.");
  138.         }
  139.         else {
  140.             System.out.println(a + " = " + b + " x " + q + " + " + r);
  141.             System.out.println(a + app.getSuffix(a) + " " + b + "의 배수(mupltiple)가 아니다.");
  142.         }
  143.     }
  144. }




실행> java MakeDivisionTableApp 500210 61

나눗셈 500210 ÷ 61 의 결과: 몫: 8200, 나머지: 10

          8200
      ________
   61 ) 500210
        488
        ------
         122
         122
        ------
            10

나머지: 10
500210 = 61 x 8200 + 10
500210은 61의 배수(mupltiple)가 아니다.




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은 세 개의 public 클래스로 구성되어 있다.
Java 소스파일에는 public 클래스가 하나만 존재해야  하므로 다음 세 개의 클래스는 각각 독립된 파일로 저장되어야 한다. 저장되는 파일명은 그 public 클래스명에 .java 라는 확장명만 붙이면 된다.
(Java 소스 코드에 public 클래스가 있을 시에는 파일명 붙이기는 언제나 이런 규칙이 적용된다.)
Java  언어는 C 언어 처럼 대소문자 구별을 엄격히 하므로 파일명이나 클래스명에서도 대소문자 구별을 철저히 지켜야 한다.

Parent는 부모 클래스이고 Child는 Parent에서 상속 받은 자식 클래스이다.


컴파일은

     javac -d . TestSubclassing.java

의 명령으로 하나만 컴파일하면 남은 두 개도 같이 컴파일된다.


// Filename: Parent.java
public class Parent {
    private String name;
    public Parent(String name) {
        this.name =  name;
    }
    public void sayName() {
        System.out.println("I am Parent, " + name);
    }
}



// Filename: Child.java
ublic class Child extends Parent {
    private String name;
    public Child(String name) {
        super(name);               // 클래스 상속시 부모 클래스 생성자 호출
        this.name =  name;
    }
    public void sayName() {
        System.out.println("I am a child, named as " + name);
    }
}



// Filename: TestSubclassing.java
public class TestSubclassing {
    public static void main(String[] args) {
        Child obj = new Child("Dooly");
        obj.sayName();
    }
}


실행> java TestSubclassing
I am a child, named as Dooly




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

콘솔에 삼각형

         *
       * *
      *   *
     *     *
    *       *
   *         *
  *           *
 *             *
*****************


을 출력하는 Java 애플리케이션을 만들어 보자. 이런 소스 코드의 작성은 학원이나 학교에서 프로그래밍 입문자에게 과제로 많이 주어지는 것 중의 하나이다. 코끼리를 보거나 만진 사람들이 저마다 그 생김새를 말할 때 제각기 다르게 표현할 수 있듯이 이런 소스 코드의 작성도 알고 보면 얼마든지 많은 방법이 있을 것이다. 여기서는 쉬운 코드 부터 작성해 보고 차츰차츰 소스를 바꾸어 가면서 Java 프로그래밍의 기초부분을 터득해 보기로 한다.

삼각형 출력 부분을 main() 메소드에서 하지 않고, 별도로 구현된 printTriange() 메소드에서 하기로 한다. 이 메소드는 public 이고 static인 메소드(또는 함수)로 선언하여 어느 것에서든지 쉽게 불러 쓸 수 있도록 하였다. 이 문서의 모든 예제 소스 코드는 메소드를 적절히 구현하여 소스에서 역할 분담을 하게 하는 것이 얼마나 중요한지 알려주기 위해 재작성된 소스 코드들이다.


우선 첫번 째 예제는 컨솔 출력 메소드 System.out.println()의 사용법만 알면 누구나 코딩할 수 있는 매우 단순한 소스 코드이다.


삼각형 출력 예제 1
/*
 *  Filename: PrintTriangleFn1.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn1.java
 *  Execute: java PrintTriangleFn1
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn1 {

    public static void printTriange() {
        System.out.println("        *        ");
        System.out.println("       * *       ");
        System.out.println("      *   *      ");
        System.out.println("     *     *     ");
        System.out.println("    *       *    ");
        System.out.println("   *         *   ");
        System.out.println("  *           *  ");
        System.out.println(" *             * ");
        System.out.println("*****************");
    }

    public static void main(String[] args) {
        printTriange();
    }
}


위의 소스 코드는 아무 알고리즘도 없는 너무 단순한 코드이다. 이런 코드를 작성했다간 출력 모양이나 크기를 변경해야 하는 상황을 맞이하면 워드프로세서로 문서 만드는 것 이상으로 많은 수작업을 하거나 아니면 포기하는 지경에 이를 수도 있다. 그래서 다음 처럼 좀 더 나은 소스 코드를 작성하였다.



삼각형 출력 예제 2
/*
 *  Filename: PrintTriangleFn2.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn2.java
 *  Execute: java PrintTriangleFn2
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn2 {

    public static void printTriange() {
        for (int i = 0; i < 8; i++) {
            for (int k = 0;  k < 8 - i; k++) {
                System.out.print(" ");
            }
            for (int k = 0;  k < 2*i + 1; k++) {
                if (k == 0 || k == 2*i)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            for (int k = 0;  k < 8 - i; k++) {
                System.out.print(" ");
            }
            System.out.println();
        }

        for (int i = 0; i < 17; i++) {
            System.out.print("*");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        printTriange();
    }
}



위의 소스 코드는 출력 메소드 System.out.println()과 System.out.print() 그리고 for 구문을 적절히 사용하여 구현되었다. 숫자 몇 곳만 수정하면 출력되는 삼각형의 크기를 바꿀 수 있다. 한 줄에 출력될 문자를 구성하는 알고리즘은 위의 예제와 근본적으로 같지만 System.out.print()를 사용하지 않고, 그대신 StringBuffer를 적절히 사용하여 한 즐씩 출력하는 소스 코드를 다음 예제와 같이 작성해 보았다.



삼각형 출력 예제 3
/*
 *  Filename: PrintTriangleFn3.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn3.java
 *  Execute: java PrintTriangleFn3
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn3 {

    public static void printTriange() {
        String line = "                 ";
        StringBuffer line2 = new StringBuffer("");
        for (int i = 0; i < 8; i++) {
            line2 = new StringBuffer(line);
            line2.setCharAt(8-i, '*');
            line2.setCharAt(8+i, '*');
            System.out.println(line2);
        }

        line2 = new StringBuffer(line);
        for (int i = 0; i < 17; i++) {
            line2.setCharAt(i, '*');
        }
        System.out.println(line2);
    }

    public static void main(String[] args) {
        printTriange();
    }
}



별(*) 문자를 이용하여 삼각형을 출력하는 일은 빈칸  문자와 별 문자를 적당한 좌표(위치)에 촐력하는 일이다. StringBuffer를 사용하더라도 한 줄의 출력을 빈칸 만으로로 구성된 string(소스 코드에서 변수 whites가 참조하는 string 값)을 기본으로 하고, 이 string에 한 두 개의 빈칸을 바꾸어 출력하는 기법으로 작성한 것이 다음 소스 코드이다. 단, 마지막 줄에 츨력될 string은 stars라는 별도의 변수로 처리하였다.


삼각형 출력 예제 4
/*
 *  Filename: PrintTriangleFn4.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn4.java
 *  Execute: java PrintTriangleFn4
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn4 {

    public static void printTriange() {
        String whites = "                 ";
        String stars  = "*****************";
        StringBuffer line2 = new StringBuffer(whites);
        line2 = line2.replace(8, 9, "*");
        System.out.println(line2);

        for (int i = 1; i < 8; i++) {
            line2 = new StringBuffer(whites);
            line2 = line2.replace(8-i, 8+i, stars.substring(8-i, 8+i));
            line2 = line2.replace(8-i+1, 8+i-1, whites.substring(8-i, 8+i-1));
            System.out.println(line2);
        }

        System.out.println(stars);
    }

    public static void main(String[] args) {
        printTriange();
    }
}




빈칸 문자를 별(*) 문자로 바꾸기 위해, 위의 소스 코드에서는 StringBuffer.replace() 메소드를 이용하였지만, 다음 소스 코드에서는 StringBuffer.setCharAt() 메소드를 이용하였다.



삼각형 출력 예제 5
/*
 *  Filename: PrintTriangleFn5.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn5.java
 *  Execute: java PrintTriangleFn5
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn5 {

    public static void printTriange() {
        String whites = "                 ";
        String stars  = "*****************";
        StringBuffer line = new StringBuffer(whites);
        int start = 8;
        line = line.replace(start, start, "*");
        System.out.println(line);

        for (int i = 1; i < 8; i++) {
            line = new StringBuffer(whites);
            line.setCharAt(start - i, stars.charAt(start - i));
            line.setCharAt(start + i, stars.charAt(start + i));
            System.out.println(line);
        }

        System.out.println(stars);
    }

    public static void main(String[] args) {
        printTriange();
    }
}




출력되는 삼각형이 좌우 대칭이라는 사실에 착안하여, 다음 소스 코드에서는  각 줄을 처음 8자, 중앙 한 문자, 끝 8자(처음 8자의 역순)로 string을 만들어 출력하였다.



삼각형 출력 예제 6
/*
 *  Filename: PrintTriangleFn6.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn6.java
 *  Execute: java PrintTriangleFn6
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn6 {

    public static void printTriange() {
        String whites = "        ";
        String stars  = "********";
        int start = 8;
        StringBuffer line = new StringBuffer(whites);
        line.append('*');
        line.append(whites);
        System.out.println(line);

        for (int i = 1; i < 8; i++) {
            line = new StringBuffer(whites);
            line.setCharAt(start - i, stars.charAt(start - i));
            System.out.print(line);
            System.out.print(" ");
            line.reverse();
            System.out.println(line);
        }

        line = new StringBuffer(stars);
        line.append('*');
        line.append(stars);
        System.out.println(line);
    }

    public static void main(String[] args) {
        printTriange();
    }
}




다음 소스 코드는 한 줄에 출력될 문자열의 데이터를 17비트 이진법 수로 구성하고, 이 이진법수의 비트가 0인 곳에는 빈칸을, 1인 곳에는 별(*)을 출력하는 기법으로 작성되었다.



삼각형 출력 예제 7
/*
 *  Filename: PrintTriangleFn7.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn7.java
 *  Execute: java PrintTriangleFn7
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn7 {

    public static void printTriange() {
        int start = 0x100;
        int total = 0;
        int val = start;
        String data;

        for (int k = 0; k < 8; k++) {
            val = (start << k) | (start >> k);
            data = Integer.toString(val, 2);
            for (int i = 0; i < 17 - data.length(); i++) {
                System.out.print(' ');
            }
            for (int i = 0; i < data.length(); i++) {
                if (data.charAt(i) == '0')
                    System.out.print(' ');
                else
                    System.out.print('*');
            }
            System.out.println();
            total += val;
        }

        val = (start << 8) | (start >> 8);
        total += val;
        data = Integer.toString(total, 2);
        for (int i = 0; i < 17 - data.length(); i++) {
            System.out.print(' ');
        }
        for (int i = 0; i < data.length(); i++) {
            if (data.charAt(i) == '0')
                System.out.print(' ');
            else
                System.out.print('*');
        }
        System.out.println();
    }

    public static void main(String[] args) {
        printTriange();
    }
}




기본적인 원리는 위의 소스 코드와 같지만 이진법수의 한 비트 마다 한 문자씩 츨력하는 대신에 출력된 한 줄의 string을 완성하여 이를 Sytem.out.println()으로 출력하는 기법으로 재작성한 것이 다음의 소스 코드이다. String.replaceAll() 메소드를 이용하여, 모든 0을 빈칸으로, 모든 1을 별(*) 문자로 바꾸었으며, 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 total을 준비하였다. for 반복 구문의 블럭 내에서 구문

            total |= val;

이 하는 일이 무엇인지 이해할 수 있으면 좋겠다.




삼각형 출력 예제 8
/*
 *  Filename: PrintTriangleFn8.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn8.java
 *  Execute: java PrintTriangleFn8
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn8 {

    public static void printTriange() {
        String zeros  = "00000000";
        int start = 0x100;
        int total = 0;
        int val = start;
        String line = "";
        String data;

        for (int k = 0; k < 8; k++) {
            val = (start << k) | (start >> k);
            data = Integer.toString(val, 2);
            line = zeros.substring(0, 17 - data.length()) + data;
            line = line.replaceAll("0", " ");
            line = line.replaceAll("1", "*");
            System.out.println(line);
            total |= val;
        }

        val = (start << 8) | (start >> 8);
        total |= val;
        line = Integer.toString(total, 2);
        line = line.replaceAll("0", " ");
        line = line.replaceAll("1", "*");
        System.out.println(line);
    }

    public static void main(String[] args) {
        printTriange();
    }
}




소스 코드가 처음 것 보다 매우 복잡해졌지만 리스트(java.util.ArrayList)를 이용해서도 할 수 있다는 것을 보여주기 위해서 일부러 작성해보았다. JDK 1.5(타이거) 부터 등장한 generics를 이용한 소스 코드이므로 JDK 1.5 이상에서 컴파일되어야 한다. 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 last를 준비하였다.



삼각형 출력 예제 9
/*
 *  Filename: PrintTriangleFn9.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn9.java
 *  Execute: java PrintTriangleFn9
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn9 {

    public static void printTriange() {
        int start = 8;
        ArrayList<String> data = new ArrayList<String>();
        ArrayList<String> last = new ArrayList<String>();

        for (int k = 0; k < 17; k++) {
            data.add(" ");
            last.add(" ");
        }
        data.set(start, "*");
        last.set(start, "*");
        for (int i = 0; i < data.size(); i++) {
            System.out.print(data.get(i));
        }
        System.out.println();
        data.set(start, " ");

        for (int k = 1; k < 8; k++) {
            data.set(start - k, "*");
            last.set(start - k, "*");
            data.set(start + k, "*");
            last.set(start + k, "*");

            for (int i = 0; i < data.size(); i++) {
                System.out.print(data.get(i));
            }
            System.out.println();
            data.set(start - k, " ");
            data.set(start + k, " ");
        }

        last.set(start - 8, "*");
        last.set(start + 8, "*");
        for (int i = 0; i < last.size(); i++) {
            System.out.print(last.get(i));
        }
        System.out.println();
    }

    public static void main(String[] args) {
        printTriange();
    }
}




다음 예제는 수학에서 xy-좌표평면에 점을 찍듯이 논리 구문

             (x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0)

가 참이 되는 위치에 별(*) 문자를 표시하는 기법으로 작성된 소스 코드이다.




삼각형 출력 예제 10
/*
 *  Filename: PrintTriangleFn10.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleFn10.java
 *  Execute: java PrintTriangleFn10
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleFn10 {

    public static void printTriange() {
        char a;
        for (int y = 0; y <= 8; y++) {
            for (int x = 0; x <= 16; x++) {
                if ((x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0))
                    a = '*';
                else
                    a = ' ';
                System.out.print(a);
            }
            System.out.println();
        }
    }
}





Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

콘솔에 삼각형

         *
       * *
      *   *
     *     *
    *       *
   *         *
  *           *
 *             *
*****************


을 출력하는 Java 애플리케이션을 만들어 보자. 이런 소스 코드의 작성은 학원이나 학교에서 프로그래밍 입문자에게 과제로 많이 주어지는 것 중의 하나이다. 코끼리를 보거나 만진 사람들이 저마다 그 생김새를 말할 때 제각기 다르게 표현할 수 있듯이 이런 소스 코드의 작성도 알고 보면 얼마든지 많은 방법이 있을 것이다. 여기서는 쉬운 코드 부터 작성해 보고 차츰차츰 소스를 바꾸어 가면서 Java 프로그래밍의 기초부분을 터득해 보기로 한다.


우선 첫번 째로 다음 예제는 컨솔 출력 메소드 System.out.println()의 사용법만 알면 누구나 코딩할 수 있는 매우 단순한 소스 코드이다.
 

삼각형 출력 예제 1
/*
 *  Filename: PrintTriangleApp1.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp1.java
 *  Execute: java PrintTriangleApp1
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp1 {
    public static void main(String[] args) {
        System.out.println("        *        ");
        System.out.println("       * *       ");
        System.out.println("      *   *      ");
        System.out.println("     *     *     ");
        System.out.println("    *       *    ");
        System.out.println("   *         *   ");
        System.out.println("  *           *  ");
        System.out.println(" *             * ");
        System.out.println("*****************");
    }
}


위의 소스 코드는 아무 알고리즘도 없는 너무 단순한 코드이다. 이런 코드를 작성했다간 출력 모양이나 크기를 변경해야 하는 상황을 맞이하면 위드프로세서로 문서 만드는 것 이상으로 많은 수작업을 하거나 아니면 포기하는 지경에 이를 수도 있다. 그래서 다음 처럼 좀 더 나은 소스 코드를 작성하였다.



삼각형 출력 예제 2
/*
 *  Filename: PrintTriangleApp2.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp2.java
 *  Execute: java PrintTriangleApp2
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp2 {
    public static void main(String[] args) {
        for (int i = 0; i < 8; i++) {
            for (int k = 0;  k < 8 - i; k++) {
                System.out.print(" ");
            }
            for (int k = 0;  k < 2*i + 1; k++) {
                if (k == 0 || k == 2*i)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            for (int k = 0;  k < 8 - i; k++) {
                System.out.print(" ");
            }
            System.out.println();
        }

        for (int i = 0; i < 17; i++) {
            System.out.print("*");
        }
        System.out.println();
    }
}


위의 소스 코드는 출력 메소드 System.out.println()과 System.out.print() 그리고 for 구문을 적절히 사용하여 구현되었다. 숫자 몇 곳만 수정하면 출력되는 삼각형의 크기를 바꿀 수 있다. 한 줄에 출력될 문자를 구성하는 알고리즘은 위의 예제와 근본적으로 같지만 System.out.print()를 사용하지 않고, 그대신 StringBuffer를 적절히 사용하여 한 즐씩 출력하는 소스 코드를 다음 예제와 같이 작성해 보았다.


삼각형 출력 예제 3
/*
 *  Filename: PrintTriangleApp3.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp3.java
 *  Execute: java PrintTriangleApp3
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp3 {
    public static void main(String[] args) {
        String line = "                 ";
        StringBuffer line2 = new StringBuffer("");
        for (int i = 0; i < 8; i++) {
            line2 = new StringBuffer(line);
            line2.setCharAt(8-i, '*');
            line2.setCharAt(8+i, '*');
            System.out.println(line2);
        }

        line2 = new StringBuffer(line);
        for (int i = 0; i < 17; i++) {
            line2.setCharAt(i, '*');
        }
        System.out.println(line2);
    }
}



별(*) 문자를 이용하여 삼각형을 출력하는 일은 빈칸  문자와 별 문자를 적당한 좌표(위치)에 촐력하는 일이다. StringBuffer를 사용하더라도 한 줄의 출력을 빈칸 만으로로 구성된 string(소스 코드에서 변수 whites가 참조하는 string 값)을 기본으로 하고, 이 string에 한 두 개의 빈칸을 바꾸어 출력하는 기법으로 작성한 것이 다음 소스 코드이다. 단, 마지막 줄에 츨력될 string은 stars라는 별도의 변수로 처리하였다.



삼각형 출력 예제 4
/*
 *  Filename: PrintTriangleApp4.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp4.java
 *  Execute: java PrintTriangleApp4
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp4 {
    public static void main(String[] args) {
        String whites = "                 ";
        String stars  = "*****************";
        StringBuffer line2 = new StringBuffer(whites);
        line2 = line2.replace(8, 9, "*");
        System.out.println(line2);

        for (int i = 1; i < 8; i++) {
            line2 = new StringBuffer(whites);
            line2 = line2.replace(8-i, 8+i, stars.substring(8-i, 8+i));
            line2 = line2.replace(8-i+1, 8+i-1, whites.substring(8-i, 8+i-1));
            System.out.println(line2);
        }

        System.out.println(stars);
    }
}




빈칸 문자를 별(*) 문자로 바꾸기 위해, 위의 소스 코드에서는 StringBuffer.replace() 메소드를 이용하였지만, 다음 소스 코드에서는 StringBuffer.setCharAt() 메소드를 이용하였다.



삼각형 출력 예제 5
/*
 *  Filename: PrintTriangleApp5.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp5.java
 *  Execute: java PrintTriangleApp5
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp5 {
    public static void main(String[] args) {
        String whites = "                 ";
        String stars  = "*****************";
        StringBuffer line = new StringBuffer(whites);
        int start = 8;
        line = line.replace(start, start, "*");
        System.out.println(line);

        for (int i = 1; i < 8; i++) {
            line = new StringBuffer(whites);
            line.setCharAt(start - i, stars.charAt(start - i));
            line.setCharAt(start + i, stars.charAt(start + i));
            System.out.println(line);
        }

        System.out.println(stars);
    }
}




출력되는 삼각형이 좌우 대칭이라는 사실에 착안하여, 다음 소스 코드에서는  각 줄을 처음 8자, 중앙 한 문자, 끝 8자(처음 8자의 역순)로 string을 만들어 출력하였다.



삼각형 출력 예제 6
/*
 *  Filename: PrintTriangleApp6.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp6.java
 *  Execute: java PrintTriangleApp6
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp6 {

    public static void main(String[] args) {
        String whites = "        ";
        String stars  = "********";
        int start = 8;
        StringBuffer line = new StringBuffer(whites);
        line.append('*');
        line.append(whites);
        System.out.println(line);

        for (int i = 1; i < 8; i++) {
            line = new StringBuffer(whites);
            line.setCharAt(start - i, stars.charAt(start - i));
            System.out.print(line);
            System.out.print(" ");
            line.reverse();
            System.out.println(line);
        }

        line = new StringBuffer(stars);
        line.append('*');
        line.append(stars);
        System.out.println(line);
    }
}




다음 소스 코드는 한 줄에 출력될 문자열의 데이터를 17비트 이진법 수로 구성하고, 이 이진법수의 비트가 0인 곳에는 빈칸을, 1인 곳에는 별(*)을 출력하는 기법으로 작성되었다.



삼각형 출력 예제 7
/*
 *  Filename: PrintTriangleApp7.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp7.java
 *  Execute: java PrintTriangleApp7
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp7 {
    public static void main(String[] args) {
        int start = 0x100;
        int total = 0;
        int val = start;
        String data;
        for (int k = 0; k < 8; k++) {
            val = (start << k) | (start >> k);
            data = Integer.toString(val, 2);
            for (int i = 0; i < 17 - data.length(); i++) {
                System.out.print(' ');
            }
            for (int i = 0; i < data.length(); i++) {
                if (data.charAt(i) == '0')
                    System.out.print(' ');
                else
                    System.out.print('*');
            }
            System.out.println();
            total += val;
        }

        val = (start << 8) | (start >> 8);
        total += val;
        data = Integer.toString(total, 2);
        for (int i = 0; i < 17 - data.length(); i++) {
            System.out.print(' ');
        }
        for (int i = 0; i < data.length(); i++) {
            if (data.charAt(i) == '0')
                System.out.print(' ');
            else
                System.out.print('*');
        }
        System.out.println();
    }
}




기본적인 원리는 위의 소스 코드와 같지만 이진법수의 한 비트 마다 한 문자씩 츨력하는 대신에 출력된 한 줄의 string을 완성하여 이를 Sytem.out.println()으로 출력하는 기법으로 재작성한 것이 다음의 소스 코드이다. String.replaceAll() 메소드를 이용하여, 모든 0을 빈칸으로, 모든 1을 별(*) 문자로 바꾸었으며, 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 total을 준비하였다. for 반복 구문의 블럭 내에서 구문

            total |= val;

이 하는 일이 무엇인지 이해할 수 있으면 좋겠다.




삼각형 출력 예제 8
/*
 *  Filename: PrintTriangleApp8.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp8.java
 *  Execute: java PrintTriangleApp8
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp8 {
    public static void main(String[] args) {
        String zeros  = "00000000";
        int start = 0x100;
        int total = 0;
        int val = start;
        String line = "";
        String data;
        for (int k = 0; k < 8; k++) {
            val = (start << k) | (start >> k);
            data = Integer.toString(val, 2);
            line = zeros.substring(0, 17 - data.length()) + data;
            line = line.replaceAll("0", " ");
            line = line.replaceAll("1", "*");
            System.out.println(line);
            total |= val;
        }

        val = (start << 8) | (start >> 8);
        total |= val;
        line = Integer.toString(total, 2);
        line = line.replaceAll("0", " ");
        line = line.replaceAll("1", "*");
        System.out.println(line);
    }
}




소스 코드가 처음 것 보다 매우 복잡해졌지만 리스트(java.util.ArrayList)를 이용해서도 할 수 있다는 것을 보여주기 위해서 일부러 작성해보았다. JDK 1.5(타이거) 부터 등장한 generics를 이용한 소스 코드이므로 JDK 1.5 이상에서 컴파일되어야 한다. 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 last를 준비하였다.



삼각형 출력 예제 9
/*
 *  Filename: PrintTriangleApp9.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp9.java
 *  Execute: java PrintTriangleApp9
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

import java.util.ArrayList;

public class PrintTriangleApp9 {
    public static void main(String[] args) {
        int start = 8;
  ArrayList<String> data = new ArrayList<String>();
  ArrayList<String> last = new ArrayList<String>();
        for (int k = 0; k < 17; k++) {
            data.add(" ");
            last.add(" ");
        }
  data.set(start, "*");
  last.set(start, "*");
        for (int i = 0; i < data.size(); i++) {
            System.out.print(data.get(i));
        }
        System.out.println();
        data.set(start, " ");

        for (int k = 1; k < 8; k++) {
            data.set(start - k, "*");
            last.set(start - k, "*");
            data.set(start + k, "*");
            last.set(start + k, "*");

            for (int i = 0; i < data.size(); i++) {
                System.out.print(data.get(i));
            }
            System.out.println();

            data.set(start - k, " ");
            data.set(start + k, " ");
        }

        last.set(start - 8, "*");
        last.set(start + 8, "*");
        for (int i = 0; i < last.size(); i++) {
            System.out.print(last.get(i));
        }
        System.out.println();
    }
}




다음 예제는 수학에서 xy-좌표평면에 점을 찍듯이 논리 구문

             (x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0)

가 참이 되는 위치에 별(*) 문자를 표시하는 기법으로 작성된 소스 코드이다.




삼각형 출력 예제 10
/*
 *  Filename: PrintTriangleApp10.java
 *            Print a triangle on console.
 *
 *  Compile: javac -d . PrintTriangleApp10.java
 *  Execute: java PrintTriangleApp10
 *
 *      Date:  2008/04/01
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

public class PrintTriangleApp10 {
    public static void main(String[] args) {
        char a;
        for (int y = 0; y <= 8; y++) {
            for (int x = 0; x <= 16; x++) {
                if ((x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0))
                    a = '*';
                else
                    a = ' ';
                System.out.print(a);
            }
            System.out.println();
        }
    }
}






Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

ASCII(애스키)란 American Standard Code for Information Interchange의 줄임글로서, 영문자에 기초한 문자 인코딩이다.  이 문자 인코딩에는 C0 제어문자(C0 control character)도 포함되어 있다.  ( 참고:  ASCII - Wikipedia, the free encyclopedia )

다음은  7bit ASCII 코드표를 만들어 보여주는 자바 소스 코드이다. 소스 코드 중에 진법변환에 필요한 메소드

        convertAtoI(String, radix)
        convertItoA(long, radix)

의 구현도 포함되어 있다.


  1. /*
  2.  *  Filename: MakeAsciiTableApp.java
  3.  *            Make a table of ascii codes.
  4.  *
  5.  *  Compile: javac -d . MakeAsciiTableApp.java
  6.  *  Execute: java MakeAsciiTableApp
  7.  *
  8.  *      Date:  2008/03/27
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. public class MakeAsciiTableApp {
  12.     static void println(String s) {
  13.         System.out.println(s);
  14.     }
  15.     static void print(String s) {
  16.         System.out.print(s);
  17.     }
  18.     static void printUsage() {
  19.         println("Usage: java MakeAsciiTableApp");
  20.         println("Make a table of ascii codes.");
  21.     }
  22.     static String BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  23.     public static String convertItoA(long num, int radix) {
  24.         long q, r;
  25.         boolean isNegative = false;
  26.         if (num < 0L) {
  27.             isNegative = true;
  28.             num = -num;
  29.         }
  30.         String arr = "";
  31.         q = num;
  32.         r = 0L;
  33.         while (q >= (long) radix) {
  34.             r = q % (long) radix;
  35.             q = q / (long) radix;
  36.             arr += BASE36.charAt((int) r);
  37.         }
  38.         arr += BASE36.charAt((int) q);
  39.         if (isNegative) {
  40.             arr += "-";
  41.         }
  42.         int n = arr.length();
  43.         String ret = "";
  44.         for (int i = 0; i < n; i++) {
  45.             ret += arr.charAt(n - i - 1);
  46.          }
  47.          return ret;
  48.     }
  49.     public static long convertAtoI(String srcStr, int radix) {
  50.         boolean isNegative = false;
  51.         long ret = 0L;
  52.         int len = srcStr.length();
  53.         char c;
  54.         int i;
  55.         long val = 0L;
  56.         c = srcStr.charAt(0);
  57.         if (c == '-') {
  58.             isNegative = true;
  59.         }
  60.         else if (c >= '0' && c <= '9') {
  61.             ret = (long) (c - '0');
  62.         }
  63.         else if (c >= 'A' && c <= 'Z') {
  64.             ret = (long) (c - 'A') + 10L;
  65.         }
  66.         else if (c >= 'a' && c <= 'z') {
  67.             ret = (long) (c - 'a') + 10L;
  68.         }
  69.         if (ret >= (long) radix) {
  70.             println("        Invalid character!");
  71.             return ret;
  72.         }
  73.         for (i = 1; i < len; i++) {
  74.             c = srcStr.charAt(i);
  75.             ret *= radix;
  76.             if (c >= '0' && c <= '9') {
  77.                 val = (long) (c - '0');
  78.             }
  79.             else if (c >= 'A' && c <= 'Z') {
  80.                 val = (long) (c - 'A') + 10L;
  81.             }
  82.             else if (c >= 'a' && c <= 'z') {
  83.                 val = (long) (c - 'a') + 10L;
  84.             }
  85.             if (val >= (long) radix) {
  86.                 println("        Invalid character!");
  87.                 return ret;
  88.             }
  89.             ret += val;
  90.         }
  91.         return ret;
  92.     }
  93.     static String[] asc  = new String[] {
  94.         "NUL", "SOH", "STX", "ETX", "EOT",
  95.         "ENQ", "ACK", "BEL", "BS", "HT",
  96.         "LF", "VT", "FF", "CR", "SO",
  97.         "SI", "DLE", "DC1", "DC2", "DC3",
  98.         "DC4", "NAK", "SYN", "ETB", "CAN",
  99.         "EM", "SUB", "ESC", "FS", "GS",
  100.         "RS", "US", "Spc"
  101.     };
  102.     static String[] control  = new String[] {
  103.         "NUL (null)",
  104.         "SOH (start of heading)",
  105.         "STX (start of text)",
  106.         "ETX (end of text)",
  107.         "EOT (end of transmission)",
  108.         "ENQ (enquiry)",
  109.         "ACK (acknowledge)",
  110.         "BEL (bell)",
  111.         "BS  (backspace)",
  112.         "TAB (horizontal tab)",
  113.         "LF  (line feed, NL new line)",
  114.        "VT  (vertical tab)",
  115.         "FF  (form feed, NP new page)",
  116.         "CR  (carriage return)",
  117.         "SO  (shift out)",
  118.         "SI  (shift in)",
  119.         "DLE (data link escape)",
  120.         "DC1 (device control 1)",
  121.         "DC2 (device control 2)",
  122.         "DC3 (device control 3)",
  123.         "DC4 (device control 4)",
  124.         "NAK (negative acknowledge)",
  125.         "SYN (synchronous idle)",
  126.         "ETB (end of trans. block)",
  127.         "CAN (cancel)",
  128.         "EM  (end of medium)",
  129.         "SUB (substitute, EOF end of file)",
  130.         "ESC (escape)",
  131.         "FS  (file separator)",
  132.         "GS  (group separator)",
  133.         "RS  (record separator)",
  134.         "US  (unit separator)",
  135.     };
  136.     public static void makeTable() {
  137.         String sbuf = "";
  138.         String abuf = "";
  139.         String tbuf = "";
  140.         int i, j;
  141.         char c;
  142.         print("    ");
  143.         for (i = 0; i < 8; i++) {
  144.             print("+----");
  145.         }
  146.         print("+");
  147.         println("");
  148.         print("    ");
  149.         print("| 0- ");
  150.         print("| 1- ");
  151.         print("| 2- ");
  152.         print("| 3- ");
  153.         print("| 4- ")
  154.         print("| 5- ");
  155.         print("| 6- ");
  156.         print("| 7- ");
  157.         print("|");
  158.         println("");
  159.         print("+---");
  160.         for (i = 0; i < 8; i++) {
  161.             print("+----");
  162.         }
  163.         print("+");
  164.         println("");
  165.         for (i = 0; i < 16; i++) {
  166.             tbuf = "";
  167.             sbuf = convertItoA((long) i, 16);
  168.             tbuf += "| " + sbuf + " ";
  169.             for (j = 0; j < 8; j++) {
  170.                 if (j*16 + i <= 32) {
  171.                    abuf = String.format("| %-3s", asc[j*16 + i]);
  172.                 }
  173.                 else if (j*16 + i == 127) {
  174.                     abuf = String.format("| %-3s", "DEL");
  175.                 }
  176.                 else {
  177.                     c = (char) (j*16 + i);
  178.                     abuf = String.format("| %2c ", c);
  179.                 }
  180.                 tbuf += abuf;
  181.             }
  182.             tbuf += "|";
  183.             println(tbuf);
  184.         }
  185.         print("+---");
  186.         for (i = 0; i < 8; i++) {
  187.             print("+----");
  188.         }
  189.         print("+");
  190.         println("");
  191.         println("");
  192.         for (i = 0; i < 16; i++) {
  193.             sbuf = String.format("%-30s",  control[i]);
  194.             tbuf = String.format("  %-34s",  control[i+16]);
  195.             print(sbuf);
  196.             println(tbuf);
  197.         }
  198.     }
  199.     public static void main(String[] args) {
  200.         if (args.length > 0 && "-h".equals(args[0])) {
  201.             printUsage();
  202.             System.exit(1);
  203.         }
  204.         makeTable();
  205.     }
  206. }




컴파일> javac -d . MakAsciiTableApp.java

실행> java MakeAsciiTableApp

    +----+----+----+----+----+----+----+----+
    | 0- | 1- | 2- | 3- | 4- | 5- | 6- | 7- |
+---+----+----+----+----+----+----+----+----+
| 0 | NUL| DLE| Spc|  0 |  @ |  P |  ` |  p |
| 1 | SOH| DC1|  ! |  1 |  A |  Q |  a |  q |
| 2 | STX| DC2|  " |  2 |  B |  R |  b |  r |
| 3 | ETX| DC3|  # |  3 |  C |  S |  c |  s |
| 4 | EOT| DC4|  $ |  4 |  D |  T |  d |  t |
| 5 | ENQ| NAK|  % |  5 |  E |  U |  e |  u |
| 6 | ACK| SYN|  & |  6 |  F |  V |  f |  v |
| 7 | BEL| ETB|  ' |  7 |  G |  W |  g |  w |
| 8 | BS | CAN|  ( |  8 |  H |  X |  h |  x |
| 9 | HT | EM |  ) |  9 |  I |  Y |  i |  y |
| A | LF | SUB|  * |  : |  J |  Z |  j |  z |
| B | VT | ESC|  + |  ; |  K |  [ |  k |  { |
| C | FF | FS |  , |  < |  L |  \ |  l |  | |
| D | CR | GS |  - |  = |  M |  ] |  m |  } |
| E | SO | RS |  . |  > |  N |  ^ |  n |  ~ |
| F | SI | US |  / |  ? |  O |  _ |  o | DEL|
+---+----+----+----+----+----+----+----+----+

NUL (null)                      DLE (data link escape)
SOH (start of heading)          DC1 (device control 1)
STX (start of text)             DC2 (device control 2)
ETX (end of text)               DC3 (device control 3)
EOT (end of transmission)       DC4 (device control 4)
ENQ (enquiry)                   NAK (negative acknowledge)
ACK (acknowledge)               SYN (synchronous idle)
BEL (bell)                      ETB (end of trans. block)
BS  (backspace)                 CAN (cancel)
TAB (horizontal tab)            EM  (end of medium)
LF  (line feed, NL new line)    SUB (substitute, EOF end of file)
VT  (vertical tab)              ESC (escape)
FF  (form feed, NP new page)    FS  (file separator)
CR  (carriage return)           GS  (group separator)
SO  (shift out)                 RS  (record separator)
SI  (shift in)                  US  (unit separator)



Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0부터 15까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 자바 소스 코드이다. 진법 변환에 필요한 메소드로는 자바에

         Integer.parseInt(String, int radix);
         Long.toString(long, int radix);

가 이미 있지만, 여기에 준하는 메소드

        convertAtoI(String, radix)
        convertItoA(long, radix)

를 자체 작성하여 사용하였다.



  1. /*
  2.  *  Filename: MakeRadixTableApp.java
  3.  *            Show the radix table with 10-, 2-, 8-, 16-radices.
  4.  *
  5.  *  Compile: javac -d . MakeRadixTableApp.java
  6.  *  Execute: java MakeRadixTableApp
  7.  *
  8.  *      Date:  2008/03/27
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. public class MakeRadixTableApp {
  12.     static void println(String s) {
  13.         System.out.println(s);
  14.     }
  15.     static void print(String s) {
  16.         System.out.print(s);
  17.     }
  18.     static void printUsage() {
  19.         println("Usage: java MakeRadixTableApp");
  20.         println("Show the radix table with 10-, 2-, 8-, 16-radices.");
  21.     }
  22.     static String BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  23.     public static String convertItoA(long num, int radix) {
  24.         long q, r;
  25.         boolean isNegative = false;
  26.         if (num < 0L) {
  27.             isNegative = true;
  28.             num = -num;
  29.         }
  30.         String arr = "";
  31.         q = num;
  32.         r = 0L;
  33.         while (q >= (long) radix) {
  34.             r = q % (long) radix;
  35.             q = q / (long) radix;
  36.             arr += BASE36.charAt((int) r);
  37.         }
  38.         arr += BASE36.charAt((int) q);
  39.         if (isNegative) {
  40.              arr += "-";
  41.         }
  42.         int n = arr.length();
  43.         String ret = "";
  44.         for (int i = 0; i < n; i++) {
  45.             ret += arr.charAt(n - i - 1);
  46.         }
  47.         return ret;
  48.     }
  49.     public static long convertAtoI(String srcStr, int radix) {
  50.         boolean isNegative = false;
  51.         long ret = 0L;
  52.         int len = srcStr.length();
  53.         char c;
  54.         int i;
  55.         long val = 0L;
  56.         c = srcStr.charAt(0);
  57.         if (c == '-') {
  58.            isNegative = true;
  59.         }
  60.         else if (c >= '0' && c <= '9') {
  61.             ret = (long) (c - '0');
  62.         }
  63.         else if (c >= 'A' && c <= 'Z') {
  64.             ret = (long) (c - 'A') + 10L;
  65.         }
  66.         else if (c >= 'a' && c <= 'z') {
  67.             ret = (long) (c - 'a') + 10L;
  68.         }
  69.         if (ret >= (long) radix) {
  70.             println("        Invalid character!");
  71.             return ret;
  72.         }
  73.         for (i = 1; i < len; i++) {
  74.             c = srcStr.charAt(i);
  75.             ret *= radix;
  76.             if (c >= '0' && c <= '9') {
  77.                 val = (long) (c - '0');
  78.             }
  79.             else if (c >= 'A' && c <= 'Z') {
  80.                 val = (long) (c - 'A') + 10L;
  81.             }
  82.             else if (c >= 'a' && c <= 'z') {
  83.                 val = (long) (c - 'a') + 10L;
  84.             }
  85.             if (val >= (long) radix) {
  86.                 println("        Invalid character!");
  87.                 return ret;
  88.             }
  89.             ret += val;
  90.         }
  91.         return ret;
  92.     }
  93.     public static void makeTable() {
  94.         String sbuf = "";
  95.         String abuf = "";
  96.         String tbuf = "";
  97.         int i, j;
  98.         char c;
  99.         for (i = 0; i < 4; i++) {
  100.             print("+-------");
  101.         }
  102.         print("+");
  103.         println("");
  104.         print("|  Dec");
  105.         print("\t|   Bin");
  106.         print("\t|  Oct");
  107.         print("\t|  Hex  |");
  108.         println("");
  109.         for (i = 0; i < 4; i++) {
  110.             print("+-------");
  111.         }
  112.         print("+");
  113.         println("");
  114.         for (i = 0; i < 16; i++) {
  115.             sbuf = String.format("|   %2d", i);
  116.             abuf = convertItoA((long) i, 2);
  117.             tbuf = String.format("\t|  %4s", abuf);
  118.             sbuf += tbuf;
  119.             abuf = convertItoA((long) i, 8);
  120.             tbuf = String.format("\t|   %2s", abuf);
  121.             sbuf += tbuf;
  122.             abuf = convertItoA((long) i, 16);
  123.             tbuf = String.format("\t|    %-2s |", abuf);
  124.             sbuf += tbuf;
  125.             println(sbuf);
  126.         }
  127.         for (i = 0; i < 4; i++) {
  128.             print("+-------");
  129.         }
  130.         print("+");
  131.         println("");
  132.     }
  133.     public static void main(String[] args) {
  134.         if (args.length > 0 && "-h".equals(args[0])) {
  135.             printUsage();
  136.             System.exit(1);
  137.         }
  138.         makeTable();
  139.     }
  140. }



컴파일> javac -d . MakeRadixTableApp.java

실행> java MakeRadixTableApp

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 자바 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Integer 클래스와 Long 클래스의 정적 메소드

         Integer.parseInt(String, int);
         Long.toString(long, int);

을 이용하였으며, 지원되는 진법은 2진법부터 36진법까지이다.



  1. /*
  2.  *  Filename: ConvertRadixApp.java
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Compile: javac -d . ConvertRadixApp.java
  6.  *  Execute: java ConvertRadixApp
  7.  *
  8.  *      Date:  2008/03/25
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. import java.io.*;
  12. import java.util.*;
  13. public class ConvertRadixApp {
  14.     public static void printUsage() {
  15.         System.out.println("Usage: java ConvertRadixApp");
  16.         System.out.println("Convert radix in a interactive mode, where the maximum radix is 36.");
  17.     }
  18.     public void printAbout() {
  19.         System.out.println("    About: Convert radix in a interactive mode.");
  20.     }
  21.     public void printMainMenu() {
  22.         System.out.println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it");
  23.     }
  24.     public void printMainPrompt() {
  25.         System.out.print("  Prompt> ");
  26.     }
  27.     public void printSubMenu(int srcRadix, int destRadix) {
  28.         System.out.println("    Convert Radix_" + srcRadix + " to Radix_" + destRadix);
  29.         System.out.println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
  30.     }
  31.     public void printSubPrompt() {
  32.         System.out.print("    Input Value>> ");
  33.     }
  34.     public String convertRadix(String s,  int srcRdx, int destRdx) {
  35.         long val;
  36.         String ret = "";
  37.         try {
  38.             val = Integer.parseInt(s, srcRdx);
  39.             ret = Long.toString(val, destRdx);
  40.             return ret.toUpperCase();
  41.         }
  42.         catch (NumberFormatException nfx) {
  43.             System.out.println("    Error: " + nfx.getMessage() + " cantains some invalid character.");
  44.             ret = "????";
  45.         }
  46.         finally {
  47.             return ret.toUpperCase();
  48.         }
  49.     }
  50.     public void doConvert(BufferedReader r, int srcRadix, int destRadix) {
  51.         String line;
  52.         String cmd;
  53.         String srcStr = "", destStr = "";
  54.         System.out.println();
  55.         printSubMenu(srcRadix, destRadix);
  56.         try {
  57.             do {
  58.                 printSubPrompt();
  59.                 while ((cmd = r.readLine()) == null) {
  60.                 }
  61.                 if ("main()".equals(cmd)) {
  62.                     return;
  63.                 }
  64.                 else if ("exit()".equals(cmd) || "quit()".equals(cmd)) {
  65.                     System.exit(0);
  66.                 }
  67.                 try {
  68.                     Integer.parseInt(cmd, srcRadix);
  69.                     srcStr = cmd;
  70.                     destStr = convertRadix(srcStr, srcRadix, destRadix);
  71.                     System.out.println("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix);
  72.                     System.out.println();
  73.                 }
  74.                 catch (NumberFormatException nfx) {
  75.                 }
  76.              } while (true);
  77.         }
  78.         catch (IOException ex) {
  79.             ex.printStackTrace();
  80.         }
  81.     }
  82.     public void doStart() {
  83.         String line;
  84.         String cmd;
  85.         int srcRadix = 10, destRadix = 10;
  86.         String srcStr = "", destStr = "";
  87.         boolean onlyOnce = true;
  88.         BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
  89.         try {
  90.             do {
  91.                 System.out.println();
  92.                 if (onlyOnce) {
  93.                     System.out.println("  The supported maximum radix is 36.");
  94.                     onlyOnce = false;
  95.                 }
  96.                 printMainMenu();
  97.                 printMainPrompt();
  98.                 while ((cmd = r.readLine()) == null) {
  99.                 }
  100.                 if ("qQxX".contains(cmd) && cmd.length() == 1) {
  101.                     System.exit(0);
  102.                 }
  103.                 else if ("aA".contains(cmd) && cmd.length() == 1) {
  104.                     printAbout();
  105.                 }
  106.                 else if ("sS".contains(cmd) && cmd.length() == 1) {
  107.                     System.out.print("  Input the source and target radices (say, 16 2): ");
  108.                     line = r.readLine();
  109.                     StringTokenizer st = new StringTokenizer(line, " ,\t");
  110.                     while (st.countTokens() < 2) {
  111.                         System.out.print("  Input the source and target radices (say, 16 2): ");
  112.                         line = r.readLine();
  113.                         st = new StringTokenizer(line, " ,\t");
  114.                     }
  115.                     srcRadix = Integer.parseInt(st.nextToken());
  116.                     destRadix = Integer.parseInt(st.nextToken());
  117.                     doConvert(r, srcRadix, destRadix);
  118.                 }
  119.             } while (true);
  120.         }
  121.         catch (IOException ex) {
  122.             ex.printStackTrace();
  123.         }
  124.     }
  125.     public static void main(String[] args) {
  126.         if (args.length > 0 && "-h".equals(args[0])) {
  127.             printUsage();
  128.             System.exit(1);
  129.         }
  130.         ConvertRadixApp app = new ConvertRadixApp();
  131.         app.doStart();
  132.     }
  133. }



컴파일> javac -d . ConvertRadixApp.java

실행> java ConvertRadixApp

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 16

    Convert Radix_10 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 256
        ( 256 )_10   --->   ( 100 )_16

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 10

    Convert Radix_16 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> FFFF
        ( FFFF )_16   --->   ( 65535 )_10

    Input Value>> exit()





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 자바 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org

  1. /*
  2.  *  Filename: TestGoldenRatioApp.java
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: javac -d . TestGoldenRatioApp.java
  6.  *
  7.  *   Execute: java TestGoldenRatioApp
  8.  *
  9.  *      Date:  2008/03/24
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. import java.util.ArrayList;
  13. public class TestGoldenRatioApp {
  14.     public static void printUsing() {
  15.         System.out.println("Using: java TestGoldenRatioApp [-h|-help]");
  16.         System.out.println("This calculates the value of the golden ratio.");
  17.     }
  18.     // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  19.     public ArrayList<Double> findQuadraticRoot(double a, double b, double c) {
  20.         double x1, x2;
  21.         if (a == 0.0) {
  22.             throw new RuntimeException("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
  23.   }
  24.         else if (b*b - 4*a*c < 0.0) {
  25.             throw new RuntimeException("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.");
  26.   }
  27.         x1 = (-b + Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
  28.         x2 = (-b - Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
  29.         ArrayList<Double> array = new ArrayList<Double>();
  30.         array.add(new Double(x1));
  31.         array.add(new Double(x2));
  32.         return array;
  33.     }
  34.     public static void main(String[] args) {
  35.        TestGoldenRatioApp app = new TestGoldenRatioApp();
  36.         if (args.length > 0 && (args[0].equals("-h") || args[0].equals("-help"))) {
  37.             app.printUsing();
  38.             System.exit(1);
  39.         }
  40.         ArrayList<Double> values = app.findQuadraticRoot(1.0, -1.0, -1.0);
  41.         double x1, x2;
  42.         x1 = values.get(0).doubleValue();
  43.         x2 = values.get(1).doubleValue();
  44.         if (x1 >= x2) {
  45.             System.out.println("The bigger root is " + x1 + ", ");
  46.             System.out.println("and the less root is " + x2 + ".");
  47.         }
  48.         else {
  49.             System.out.println("The bigger root is " + x2 + ", ");
  50.             System.out.println("and the less root is " + x1 + ".");
  51.         }
  52.     }
  53. }



컴파일> javac -d . TestGoldenRatioApp.java

실행> java TestGoldenRatioApp
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Java 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. /*
  2.  *  Filename: TestCTimeApp.java
  3.  *
  4.  *  Compile: javac -d . TestCTimeApp.java
  5.  *
  6.  *  Execute: java TestCTimeApp
  7.  */
  8. import java.util.Calendar;
  9. import java.util.GregorianCalendar;
  10. public class TestCTimeApp {
  11.    static String[] weekNames = {
  12.                   "일", "월", "화", "수", "목", "금", "토"
  13.               };
  14.    public static void main(String[] args) {
  15.         Calendar now = new GregorianCalendar();
  16.         // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  17.         System.out.println("UTC: " + (now.getTime().getTime() / 1000L) + "초");
  18.         // 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  19.         System.out.print(now.get(Calendar.YEAR) + "년 ");
  20.         System.out.print((1 + now.get(Calendar.MONTH)) + "월 ");
  21.         System.out.print(now.get(Calendar.DAY_OF_MONTH) + "일 ");
  22.         System.out.print("(" + weekNames[now.get(Calendar.DAY_OF_WEEK)] + "요일) ");
  23.         System.out.print(now.get(Calendar.HOUR_OF_DAY) + "시 ");
  24.         System.out.print(now.get(Calendar.MINUTE) + "분 ");
  25.         System.out.println(now.get(Calendar.SECOND) + "초");
  26.         // 1월 1일은 1, 1월 2일은 2
  27.         System.out.print("올해 몇 번째 날: " + now.get(Calendar.DAY_OF_YEAR) + ", ");
  28.         // 0 이면 서머타임 없음
  29.         System.out.println("서머타임 적용 여부: " + (now.get(Calendar.DST_OFFSET) == 0 ? "안함" : "함"));
  30.     }
  31. }



컴파일> javac -d . TestCTimeApp.java

실행> java TestCTimeApp
UTC: 1206323913초
2008년 3월 24일 (화요일) 10시 58분 33초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,