1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy
Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Answer to Monday's Programming Question

Sunday November 30, 2008

Monday's question was to modify the code point program to use a JOptionPane. It needed to show the Unicode characters for the code point range of U+3041 to U+309F. The characters are for Hiragana, used in writing Japanese:

ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞ
ただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼ
ぽまみむめもゃやゅゆょよらりるれろゎわゐゑをんゔゕゖ゗゘゙゚
゛゜ゝゞゟ

Here's my version of the program:

import java.util.Scanner;
import javax.swing.JOptionPane;

public class DialogCodePoints {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter in first Unicode code point (e.g., U+0021): ");
    String startCodePoint = input.nextLine();
    System.out.println("Enter in last Unicode code point (e.g., U+007F}: ");
    String lastCodePoint = input.nextLine();

    StringBuffer sb = new StringBuffer();
    //The substring is the hexadecimal number (e.g., U+0021 without the "U+").
    //It can then be converted to an int by using a radix of 16
    int hexStartCodePoint = Integer.parseInt(startCodePoint.substring(2),16);
    int hexLastCodePoint = Integer.parseInt(lastCodePoint.substring(2),16);

    int wrapCount = 0;
    for (int hexCodePoint = hexStartCodePoint; hexCodePoint < hexLastCodePoint+1;hexCodePoint++)
    {
      //The toChars method will convert a Unicode Code Point to
      /its UTF-16 representation.
      sb.append(Character.toChars(hexCodePoint));

      //Add a newline every 50 characters to control the size
      //of the dialog box.
      wrapCount++;
      if (wrapCount == 50)
      {
        sb.append("\n");
        wrapCount = 0;
      }
    }

    //Create a JOptionPane to display the Unicode Characters
    JOptionPane.showMessageDialog(null, sb, "Characters", JOptionPane.INFORMATION_MESSAGE );
  }
}
Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore Java
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.