数値

프로그래밍 2011. 7. 7. 16:32

数値

コンピュータは計算が得意であるということは、誰もが知ってる常識です
当然、プログラムのソースの大部分は計算と制御で埋め尽くされるでしょう

プログラムでは、数値や文字列を直接記述したものをリテラルと呼びます
データには様々ながあり、代表どころでは整数、浮動小数、文字などがあります
数値を使った演算は主に整数型のリテラルで表現することができます

C#の整数型は、0 ~ 9 を使った10進数と、0 ~ F を使った16進数を使用できます
10進数はそのまま、16進数の場合は数値の前に 0x プリフィックスを付加する必要があります
なお、16進数のA~Fは小文字で指定しても問題はありません
class Test {
	static void Main() {
		System.Console.WriteLine(1983);
		System.Console.WriteLine("-ビル・ゲイツが Windows を発表-");

		System.Console.WriteLine(0x7C1);
		System.Console.WriteLine("-Microsoft が Windows をリリース-");
	}
}
このプログラムでは WriteLine() メソッドに 1983 という10進整数値と
7C1 という16進整数値(10進数の 1985)を渡しています
WriteLine() メソッドは、この数値を文字列に変換しコンソールに出力します

ただし、16進数も10進数も機械語では2進数なので
これらはコンパイラが扱うものであり、機械語レベルでは同じ扱いです
そのため、文字列に変換して表示した時は10進数で表示されてしまいます


実数値

プログラムが小数も扱う場合は、整数型ではなく実数型を使用します
実数リテラルは整数と違い10進数しか扱えないので注意してください

実数型は、10進整数部と小数以下の10進指数部からなります
プログラムでは小数を浮動小数点と呼ばれる方法で表現します
基本的には、数学同様に 整数部.小数部 という形で表せます
ただし浮動小数は、アンダーフローや丸め誤差と呼ばれる誤差が発生するので
その扱いにはある程度のコンピュータ科学知識が必要になることがあります

実数型は、指数表記 e または E を使用することができます
指数表記は10の累乗を表すもので 4e3 で 4000 というように表すことができます
class Test {
	static void Main() {
		System.Console.WriteLine(42.195);
		System.Console.WriteLine(0.3e-2);		
	}
}
このプログラムも、実数を問題なくコンソールに出力してくれることでしょう


文字と文字列

C# の文字は様々な国の言語を表現できる国際的な Unicode を使用しています
これは、近年 Java や Windows NT などにも積極的にとり入れられている重要な文字コードで
アプリケーション開発の国際化の時代に非常に貢献している技術です

Unicode は 2 バイト文字であり、C# は1文字に2バイトの容量を使用します
これは、C/C++ の ASCII に比べて大きく異なる点の一つです

文字はシングルクォーテーション 'で囲むことで表現できます
文字列と違い、文字型は2バイトまでと定められているため1文字しか表せません
class Test {
	static void Main() {
		System.Console.WriteLine('A');
		System.Console.WriteLine('1');
	}
}
このプログラムは WriteLine() メソッドに文字を渡して表示します
注意してほしいのですが '1' というのは数値ではなく文字型としての 1 です
表示された時は 1 としかありませんが、データ型が違うというのは重要です
この後に紹介する計算などの時には、データ型の違いは重要な項目になります

文字列は、前回紹介したようにダブルクォーテーション " で囲むことで表現できました
しかし、改行などは文字列の中で表現できませんでした
改行やタブのような特殊な文字はエスケープ文字 \と呼ばれる文字で表現します

エスケープ文字は \ で始まりその後に何らかの文字などを付加します
これをエスケープシーケンスと呼び、次のものがあります

エスケープシーケンス 説明 Unicode
\' シングルクォーテーション 0x0027
\" ダブルクォーテーション 0x0022
\\ 円マーク 0x005C
\0 null 0x0000
\a アラート 0x0007
\b バックスペース 0x0008
\f 改ページ 0x000C
\n 改行 0x000A
\r キャリッジリターン 0x000D
\t 水平タブ 0x0009
\v 垂直タブ 0x000B
\x16進数 16進エスケープシーケンス

これらのエスケープシーケンスを文字、または文字列に含ませて出力すると
それぞれのエスケープシーケンスの意味する文字を出力することができます
これを使用すれば、文字列内に " を表示させることが出きるようになります

ただし、文字列において \ に続く文字は上のいずれかのエスケープシーケンスである必要があります
class Test {
	static void Main() {
		System.Console.WriteLine("Kitty on your lap\nTokyo mew mew");
		System.Console.WriteLine("\"Nekoneko Zoo\"");
		System.Console.WriteLine("\x005C\x0009\x005C");
	}
}
これをコンパイルして実行すると、次のようになります
Kitty on your lap
Tokyo mew mew
"Nekoneko Zoo"
\       \
このように、改行コードやタブをエスケープシーケンスで表現できます
これは C/C++ の経験者であればお馴染みのものでしょう

C# は、上のように " " で囲まれた文字列を標準文字列と呼びます
これに対し、逐語的文字列と呼ばれる便利な文字列表現もあります

逐語的文字列は、標準文字列と違い " 以外の全ての文字を文字列内に指定できます
標準文字列では文字列中に改行することはできませんでしたが
逐語的文字列はタブ、改行、エスケープ文字などが全てそのまま解釈されます
ただし、逐語的文字列内で " を表現したい場合は "" と記述します

逐語的文字列は @" ではじまり " で終わります
class Test {
	static void Main() {
		System.Console.WriteLine(
@"\Kitty on your lap\
\n	Tokyo mew mew	\t
""Di Gi Charat"""
		);
	}
}
これを実行すると、次のような文字列が出力されます
\Kitty on your lap\
\n	Tokyo mew mew	\t
"Di Gi Charat"
これを見れば、エスケープ文字は解釈されずにそのまま解釈され
タブや改行も表現されていることが確認できます


Posted by 김반장78
,
별 내용 아닌데 정보가 없어 한참 고생하기

1. 옵션에 클래스패스 선택 - 폴더 추가선택 - 컴파일된 클래스폴더의 루트폴더를 선택 - 저장

2.레포트쿼리 선택 - JavaBean탭 선택 - 클래스명에 해당 클래스명 직접 입력 - 속성취득버튼 클릭

'프로그래밍' 카테고리의 다른 글

数値  (0) 2011.07.07
[펌] 자바 파일 입출력시 글자깨짐 문제  (0) 2010.12.27
[JAVA] XmlWriter.java  (0) 2010.12.10
C# 과 JAVA 의 이스케이프 코드 차이점  (0) 2010.12.09
[NetBeans] setDisable() 관련 문제  (0) 2010.11.25
Posted by 김반장78
,
일단. 어떤것을 쓰던간에.. 화일은 잘 읽힌다.. 또한 유니코드의 경우 는 더욱더 편하게 읽힌다.
문제는... 유니코드가 아닌화일을 읽을때 글자깨짐이 일어난다는 점이다.
다음의 경우 Shift_JIS 화일을 읽어들인다. 글자 안깨진다...
다음의 method를 보면 알겠지만.. 인코딩 관련 지정이 하나도 없다..
왜일까? 인코딩을 사용하면 도리어 글자가 깨진다..왜지?

/** ディレクトリからファイルを読取って文字列に返す。
  * @param workName 作業名
  * @return
  */
 public void inputFile(String fileName) {
  BufferedInputStream is = null;       // inputStream初期化
  try {
     StringBuffer returnStr = new StringBuffer();     // ファイル内容を文字列で格納するStringBuffer。

    File inputFile = new File(fileName);       // ファイルを宣言する。
    if (inputFile.isFile() && inputFile.exists() ) {    // ファイルが存在するのを確認
     is = new BufferedInputStream(new FileInputStream(fileName));  // ファイルをstreamで読み取る。
     byte[] byteBuf =new byte[(int) inputFile.length()];  // 一時的にファイルをByteで格納するbyte配列
     for(int j = 0; j < (int) inputFile.length() ; j++) {
      byteBuf[j] = (byte) is.read();       // ファイルをByte読み取る。
/* 바로 이부분이다..왜 바이트로 읽는냐..바보 아니냐 하겠지만..
   다 이유가 있다... 한자 때문이다. Shift_JIS와 unicode는 100%호완되지 않기 때문에.
MS사이트에서 뒤지면 코드 변환표가 나온다..
자바는 내부적으로 유니코드로 처리하기 때문에..
reader를 사용하면.. 깨지는 글자가 생기기 때문이다..
reader에 인코딩 지정해도..결국 깨지는 글자가 발생했다..쩝..왜..그럴리가 없어야 되는데말이지.
단순히 커뮤니티 정도 만들려면..굳이 이렇게 쓸필요없지만..공공기관용을 만들어야 한다면..
어쩔수 없다... 아직까지는..더 좋은 방법을 찾지 못했다는말이지..
*/
     }
     returnStr.append(new String(byteBuf));      // ファイル内容を文字列で格納する。

    } // if (f.isFile() && f.exists()
    is.close();

  } catch (UnsupportedEncodingException e) {    // 支援しないコードの場合
   logger.error("지원하지 않는 인코딩", e);
  } catch (FileNotFoundException e) {      // ファイルが存在しない場合
   logger.error("화일을 찾을수 없다", e);
  } catch (IOException e) {        // 入出力エラーの場合
   logger.error("입출력에러", e);
  } catch (NullPointerException e) {      // 引数がNullの場合
   logger.error("null발생", e);
  }finally{
   try {
    if (is != null) is.close();      // 最後に inputStream を閉じられなかった場合閉じる。
   } catch (IOException e) {       // 入出エラー場合
      }
  } //finally

 } // inputFile(String fileName)

/**ファイル出力処理を行う。 화일 출력이다..뭐..출력은..그다지 상관 없다...잘 되니까..
  * @param str 受け取って編集済みデータ 받아와서 편집끝낸 화일내용
  * @param date 日付 시스템 날짜
  */
 public void outputFile(String str, String fileName ) {

  OutputStreamWriter os = null;       // 出力streamWriterの初期化 초기화..
  try {
   os = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(fileName)),"Shift_JIS"); // ファイル出力する。
   os.write(str);          // ファイル内容を記録する。 화일내용을 쓰는 부분..
   os.flush();           // ファイルを放出する。(生成する) 화일을 출력하는부분.
  } catch (IOException e) {        // 入出力エラーの場合
   logger.error("IO에러", e);
  } finally { //연습할때는 finally부분까지는 필요 없다.. 에러처리라는게..연습목적은 아니니까..
   try {
    if (os != null) os.close();      // 最後に outputStream を閉じられなかった場合閉じる。
   } catch (IOException e1) {       // 入出エラー場合
    logger.error("IO에러 ",e1);
   }
  } // finally
  } //outputFile(String str, String date)

이렇게 해서 Shift_JIS에서 화일 입출력은 끝냈따..
그럼 UTF-8화일일 경우에는?
자신이 편한대로 하면 된다..
 /** ファイル読み取る。
  * @param strAddress ファイル住所
  * @return ファイル値文字列
  */
 public String inputFile(String strAddress){
  DataInputStream is = null;       // データinputStream初期化
  StringBuffer returnStr = new StringBuffer();
  try {
   File tempfile = new File (strAddress);    // ファイル宣言
   if(tempfile.exists()){       // ファイルが存在する場合
    byte[] byteBuf = new byte[(int) tempfile.length()];  // 一時的にコード変換ファイルを格納するbyte配列
    is = new DataInputStream(new BufferedInputStream(new FileInputStream(tempfile))); // ファイルinputStream宣言
    while (is.read(byteBuf, 0, byteBuf.length) != -1){   // ファイル読み取る。
     returnStr.append(new String(byteBuf, "UTF-8"));   // ファイル内容を文字列で格納する。
    } //while
   } // if (tempfile.exists()
   is.close();  

  } catch (FileNotFoundException e) {     // ファイルが存在しない場合
   logger.error("화일 안보여", e);
  } catch (IOException e) {       // 入出力エラーの場合
   logger.error("IO에러다", e);  
  }finally{
   try {
    if (is != null) is.close();     // 最後に inputStream を閉じられなかった場合閉じる。
   } catch (IOException e) {     // 入出エラー場合
   logger.error("IO에러다", e);  
   }
  } //finally
  return returnStr.toString();
 } // end od inputFile


Posted by 김반장78
,
import java.io.IOException;
import java.io.Writer;

import java.util.Stack;

import com.generationjava.io.WritingException;

/**
* Makes writing XML much much easier.
*
* @author <a href="mailto:bayard@generationjava.com">Henri Yandell</a>
* @version 0.1
*/

public class XmlWriter {

    private Writer writer;      // underlying writer
    private Stack stack;        // of xml entity names
    private StringBuffer attrs; // current attribute string
    private boolean empty;      // is the current node empty
    private boolean closed;     // is the current node closed...

    /**
     * Create an XmlWriter on top of an existing java.io.Writer.
     */

    public XmlWriter(Writer writer) {
        this.writer = writer;
        this.closed = true;
        this.stack = new Stack();
    }

    /**
     * Begin to output an entity.
     *
     * @param String name of entity.
     */

    public XmlWriter writeEntity(String name) throws WritingException {
        try {
            closeOpeningTag();
            this.closed = false;
            this.writer.write("<");
            this.writer.write(name);
            stack.add(name);
            this.empty = true;
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    // close off the opening tag
    private void closeOpeningTag() throws IOException {
        if (!this.closed) {
            writeAttributes();
            this.closed = true;
            this.writer.write(">");
        }
    }

    // write out all current attributes
    private void writeAttributes() throws IOException {
        if (this.attrs != null) {
            this.writer.write(this.attrs.toString());
            this.attrs.setLength(0);
            this.empty = false;
        }
    }

    /**
     * Write an attribute out for the current entity.
     * Any xml characters in the value are escaped.
     * Currently it does not actually throw the exception, but
     * the api is set that way for future changes.
     *
     * @param String name of attribute.
     * @param String value of attribute.
     */

    public XmlWriter writeAttribute(String attr, String value) throws WritingException {

        // maintain api
        if (false) throw new XmlWritingException();

        if (this.attrs == null) {
            this.attrs = new StringBuffer();
        }
        this.attrs.append(" ");
        this.attrs.append(attr);
        this.attrs.append("=\"");
        this.attrs.append(escapeXml(value));
        this.attrs.append("\"");
        return this;
    }

    /**
     * End the current entity. This will throw an exception
     * if it is called when there is not a currently open
     * entity.
     */

    public XmlWriter endEntity() throws WritingException {
        try {
            if(this.stack.empty()) {
                throw new XmlWritingException("Called endEntity too many times. ");
            }
            String name = (String)this.stack.pop();
            if (name != null) {
                if (this.empty) {
                    writeAttributes();
                    this.writer.write("/>");
                } else {
                    this.writer.write("</");
                    this.writer.write(name);
                    this.writer.write(">");
                }
                this.empty = false;
            }
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    /**
     * Close this writer. It does not close the underlying
     * writer, but does throw an exception if there are
     * as yet unclosed tags.
     */

    public void close() throws WritingException {
        if(!this.stack.empty()) {
            throw new XmlWritingException("Tags are not all closed. "+
                "Possibly, "+this.stack.pop()+" is unclosed. ");
        }
    }

    /**
     * Output body text. Any xml characters are escaped.
     */

    public XmlWriter writeText(String text) throws WritingException {
        try {
            closeOpeningTag();
            this.empty = false;
            this.writer.write(escapeXml(text));
            return this;
        } catch (IOException ioe) {
            throw new XmlWritingException(ioe);
        }
    }

    // Static functions lifted from generationjava helper classes
    // to make the jar smaller.
   
    // from XmlW
    static public String escapeXml(String str) {
        str = replaceString(str,"&","&amp;");
        str = replaceString(str,"<","&lt;");
        str = replaceString(str,">","&gt;");
        str = replaceString(str,"\"","&quot;");
        str = replaceString(str,"'","&apos;");
        return str;
    } 

    // from StringW
    static public String replaceString(String text, String repl, String with) {
        return replaceString(text, repl, with, -1);
    } 
    /**
     * Replace a string with another string inside a larger string, for
     * the first n values of the search string.
     *
     * @param text String to do search and replace in
     * @param repl String to search for
     * @param with String to replace with
     * @param n    int    values to replace
     *
     * @return String with n values replacEd
     */

    static public String replaceString(String text, String repl, String with, int max) {
        if(text == null) {
            return null;
        }

        StringBuffer buffer = new StringBuffer(text.length());
        int start = 0;
        int end = 0;
        while( (end = text.indexOf(repl, start)) != -1 ) {
            buffer.append(text.substring(start, end)).append(with);
            start = end + repl.length();

            if(--max == 0) {
                break;
            }
        }
        buffer.append(text.substring(start));

        return buffer.toString();
    }             

    // Two example methods. They should output the same XML:
    // <person name="fred" age="12"><phone>425343</phone><bob/></person>
    static public void main(String[] args) throws WritingException {
        test1();
        test2();
    }
    static public void test1() throws WritingException {
        Writer writer = new java.io.StringWriter();
        XmlWriter xmlwriter = new XmlWriter(writer);
        xmlwriter.writeEntity("person").writeAttribute("name", "fred").writeAttribute("age", "12").writeEntity("phone").writeText("4254343").endEntity().writeEntity("bob").endEntity().endEntity();
        xmlwriter.close();
        System.err.println(writer.toString());
    }
    static public void test2() throws WritingException {
        Writer writer = new java.io.StringWriter();
        XmlWriter xmlwriter = new XmlWriter(writer);
        xmlwriter.writeEntity("person");
        xmlwriter.writeAttribute("name", "fred");
        xmlwriter.writeAttribute("age", "12");
        xmlwriter.writeEntity("phone");
        xmlwriter.writeText("4254343");
        xmlwriter.endEntity();
        xmlwriter.writeEntity("bob");
        xmlwriter.endEntity();
        xmlwriter.endEntity();
        xmlwriter.close();
        System.err.println(writer.toString());
    }
}

C#에는 있는데 왜 자바에는 없는거냐..ㅡ.ㅡ



Posted by 김반장78
,
  • Escape sequences

    inside char and String literals include:
    ' ' space
    '\u003f' Unicode hex, (must be exactly 4 digits to give a 16-bit Unicode number ). \u2007 is Figure Space, a space as wide as a digit, to help in aligning numbers.
    '\n' newline, ctrl-J (10, x0A)
    '\b' backspace, ctrl-H (8, 0x08)
    '\f' formfeed, ctrl-L (12, 0x0C)
    '\r' carriage return, ctrl-M (13, 0x0D)
    '\t' tab, ctrl-I (9, 0x09)
    '\\' backslash,
    '\'' single quote (optional inside " "),
    '\"' double quote (optional inside ' '),
    '\377' octal (must be exactly 3 digits. You can get away with fewer, but then you create an ambiguity if the character following the literal just happens to be in the range 0..7.). This lets you get at only the 8-bit characters in the range 0..377 octal or 0..255 decimal or 0..255 decimal, which still gives you 16-bit Unicode.
    \007 bel, ctrl-G (7, 0x07)
    \010 backspace, ctrl-H (8, 0x08)
    \013 vt vertical tab, ctrl-K (11, 0x0B)
    \032 sub (used in DOS/CPM as eof), ctrl-Z (26, 0x1A)
    \033 esc ctrl-^ (27, 0x1B)
  •  

  • C# Escape sequences


  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \\ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)
  • C# \xn[n][n][n] 의 추가 설명
    16진수 이스케이프 시퀀스에는 다양한 자릿수의 16진수를 사용할 수 있습니다. 문자열 리터럴 "\x123"에는 16진수 값이 123인 문자 하나가 포함됩니다. 16진수 값이 12인 문자 다음에 문자 3이 오는 문자열을 만들려면 "\x00123"이나 "\x12" + "3"을 사용하십시오.

    Posted by 김반장78
    ,
    우회해서 짜는 방법이 여렀있었으나 가장 마음에 든건..
    CardLayout 활용

    ....
    Container ct;

    CardLayout card;
    JPanel card1;
    JPanel card2;

    ct.add(card1, "card1");
    ct.add(card2, "card2");

    card.show(ct, "card1");
    ....




    Posted by 김반장78
    ,

    <SCRIPT LANGUAGE="JavaScript">
    function zipcodeCheck(form) {
     var flag = form.frm.zipflag;
     if (flag.value == "2") {
      form.frm.adress.focus();
      form.frm.adress.value = form.frm.adress.value;
     } else if (flag.value == "1") {
      alert("郵便番号を確認");
      form.frm.post_front.focus();
     } else {
      form.frm.sex[0].checked = true;
      form.frm.bortype.checked = true;
      form.frm.name_family.focus();
     }
    }
    </SCRIPT>

    <body onload="zipcodeCheck(this)">

    어쩌다보니 자바스크립트를 하고 있다는..ㅡ.ㅡ
    그래도 2~3년밖에 안됐는데 이렇게 기억이 안나다니..

    주요 체크포인트는
    1. 펑션 밖에서는 객체를 못불러온다
    2. 버튼그룹의 경우 두개이상일때는 배열로 한개일 경우엔 객체로 매핑된다.

    Posted by 김반장78
    ,