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

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

울 이용하였으며, 지원되는 진법은 2진법에서 36진법 까지이다. 참고로 Java의 Long 타입과 Scala의 Long 타입은 다르므로, 여기서는 java.lang.Long.toString 처럼 Long 타입의 패키지명을 꼭 붙여야 한다. Scala에는 Integer 타입 대신 Int 타입을 쓰므로 Integer.parseInt는 그대로 써도 된다.

Scala 언어의 try ... catch ... finally ... 구문은

        try {
              블럭
        }
        catch {
             case e1 : 예외타입 =>
                  블럭
             case e2 : 예외타입 =>
                  블럭
        }
        finally {
              블럭
        }




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



실행> scala convertRadix.scala

  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): 16 2

    Convert Radix_16 to Radix_2
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1FF
        ( 1FF )_16   --->   ( 111111111 )_2

    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): 2 8

    Convert Radix_2 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 1011001
        ( 1011001 )_2   --->   ( 131 )_8

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> x




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


Posted by Scripter
,