목차

1.3000을 3,000으로 변경
2.문자열에서 특정위치 문자의 유니코드 값을 알아내는 방법
3.입력 받는 값이 숫자로만 되어 있는지 문자로만 되어있는지를 아는 방법
4.절대 경로가 모두 명시된 파일 이름에서 파일 이름만 추출해내는 방법
5.한글문자열을 일정한 길이만큼 보여줄 때 마지막에 한글이 잘리지 않게하는 방법
6.소숫점 처리 (자리수, 올림, 내림)
7.대문자 -> 소문자, 소문자 -> 대문자
8.E-Mail 주소 Check
9.데이터 구조
10.Date & Time 출력



1.3000을 3,000으로 변경



NumberFormat df = new DecimalFormat("#,##0.##");
String t = df.format(3000);
System.out.println(t);



2.문자열에서 특정위치 문자의 유니코드 값을 알아내는 방법



NumberFormat df = new DecimalFormat("#,##0.##");
String t = df.format(3000);
System.out.println(t);



3.입력 받는 값이 숫자로만 되어 있는지 문자로만 되어있는지를 아는 방법


boolean number = allNumbers("1234567890");
boolean nonascii = containsNonASCII("2 1 은 2");
boolean onlyascii = containsOnlyASCII("2 2 는 4");
System.out.println(number + ", " + nonascii + ", " + onlyascii);

public static boolean allNumbers(String s) {
    if (s == null || s.length() == 0)
        return false;
    char c;
    for (int i = 0; i < s.length(); i++) {
        c = s.charAt(i);
        if (c < '0' || c > '9')
            return false;
    }
    return true;
}

public static boolean containsNonASCII(String s) {
    if (s == null || s.length() == 0)
        return false;
    char c;
    for (int i = 0; i < s.length(); i++) {
        c = s.charAt(i);
        if ((c & 0xFF80) != 0)
            return true;
    }
    return false;
}

public static boolean containsOnlyASCII(String s) {
    if (s == null || s.length() == 0)
        return false;
    char c;
    for (int i = 0; i < s.length(); i++) {
        c = s.charAt(i);
        if ((c & 0xFF80) != 0)
            return false;
    }
    return true;
}



4.절대 경로가 모두 명시된 파일 이름에서 파일 이름만 추출해내는 방법



// 예를 들어 인수로 /home/foo/bar/xyz.tar.gz 가 주어진다면 결과값으로
// xyz.tar.gz 를 구하고자 합니다.
// 패스중 디렉토리 부분은 dir 에, 실제 이름은 filename 에 들어갑니다.
String path = "/home/foo/bar/xyz.tar.gz";
String filename = path;
String dir = "";
int n = filename.lastIndexOf("/");
if (n >= 0) {
    dir = filename.substring(0, n);
    filename = filename.substring(n + 1);
    if (n == 0)
        dir = "/";
}
System.out.println("path = " + path);
System.out.println("Tokenizing...    dir = " + dir + ", filename = " + filename);

////////////////////////////////////////////////////////////////////////////
// 예를 들어 인수로 C:\\\home\\foo\\bar\\abc.zip 가 주어진다면 결과값으로
// abc.zip 를 구하고자 합니다.
// 패스중 디렉토리 부분은 dir2 에, 실제 이름은 filename2 에 들어갑니다.
String path2 = "C:\\home\\foo\\bar\\abc.zip";
String filename2 = path2;
String dir2 = "";
int n2 = filename2.lastIndexOf("\\");
if (n2 >= 0) {
    dir2 = filename2.substring(0, n2);
    filename2 = filename2.substring(n2 + 1);
    if (dir2.endsWith(":"))
        dir2 += "\\";
}
System.out.println("path2 = " + path2);
System.out.println("Tokenizing...    dir2 = " + dir2 + ", filename2 = " + filename2);



5.한글문자열을 일정한 길이만큼 보여줄 때 마지막에 한글이 잘리지 않게하는 방법


자바의 경우 해당 사항 없음

단, 스트링으로 바꾸기 전의 바이트 배열이라면 30바이트 이내로 자르기

byte[] bytes = "싱글벙글 아줌마 투덜투덜 아저씨 아줌마가 펼치는 꿈속같은 이야기..".getBytes();
byte[] cuttedBytes = cutBytes(bytes, 30);
String str = new String(cuttedBytes);
System.out.println("[" + str + "]");

public static byte[] cutBytes(byte[] data, int cutLen) {
    byte[] tmp;
    int len = data.length;
    if (len <= cutLen) {
        tmp = new byte[len];
        System.arraycopy(data, 0, tmp, 0, len);
        return tmp;
    }
    else if (cutLen > 0) {
       int pos = cutLen - 1;
       while (pos > 0 && (data[pos] & 0x80) == 0x80) {
           pos--;
       }
       if ((cutLen - pos) % 2 == 0) {
           tmp = new byte[cutLen];
           System.arraycopy(data, 0, tmp, 0, cutLen);
       }
       else {
           tmp = new byte[cutLen - 1];
           System.arraycopy(data, 0, tmp, 0, cutLen - 1);
       }
       return tmp;
    }
    return null;
}

--MORE--

6.소숫점 처리 (자리수, 올림, 내림)


코드
--------------------------------------------------------------
double num = 3.141592654;
MumberFormat df = new DecimalFormat("#.00");
String str = df.format(num);
System.out.println(str);
--------------------------------------------------------------

결과
--------------------------------------------------------------
3.14
--------------------------------------------------------------

서비스 하나더 (올림,내림)

코드
--------------------------------------------------------------
int ceil = (int) Math.ceil(3.5);
int floor = (int) Math.floor(3.5);
System.out.println("올림 : " + ceil);
System.out.println("내림 : " + floor);
--------------------------------------------------------------

결과
--------------------------------------------------------------
올림 : 4
내림 : 3
--------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////////////
// @(#)TruncateTest.java  2003/08/22
//
//     절삭(truncate), 반올림(round), 잘라올림(ceil)을 잘라내림(floor)을 자유자재로
//
public class TruncateTest {
    public void doTest() {
        ///////////////////////////////////////////////////////
        // 절삭(truncate) 테스트
        System.out.println(truncate(Math.PI, 1));
        System.out.println(truncate(Math.PI, 2));
        System.out.println(truncate(Math.PI, 3));
        System.out.println(truncate(Math.PI, 4));
        System.out.println(truncate(Math.PI, 5));
        System.out.println(truncate(-Math.PI, 1));
        System.out.println(truncate(-Math.PI, 2));
        System.out.println(truncate(-Math.PI, 3));
        System.out.println(truncate(-Math.PI, 4));
        System.out.println(truncate(-Math.PI, 5));
        System.out.println(truncate(Math.PI*100000, 0));
        System.out.println(truncate(Math.PI*100000, -1));
        System.out.println(truncate(Math.PI*100000, -2));
        System.out.println(truncate(Math.PI*100000, -3));
        System.out.println(truncate(Math.PI*100000, -4));
        System.out.println(truncate(Math.PI*100000, -5));
        System.out.println(truncate(-Math.PI*100000, 0));
        System.out.println(truncate(-Math.PI*100000, -1));
        System.out.println(truncate(-Math.PI*100000, -2));
        System.out.println(truncate(-Math.PI*100000, -3));
        System.out.println(truncate(-Math.PI*100000, -4));
        System.out.println(truncate(-Math.PI*100000, -5));

        System.out.println(ceil(Math.PI, 1));
        System.out.println(ceil(Math.PI, 2));
        System.out.println(ceil(Math.PI, 3));
        System.out.println(ceil(Math.PI, 4));
        System.out.println(ceil(Math.PI, 5));
        System.out.println(ceil(-Math.PI, 1));
        System.out.println(ceil(-Math.PI, 2));
        System.out.println(ceil(-Math.PI, 3));
        System.out.println(ceil(-Math.PI, 4));
        System.out.println(ceil(-Math.PI, 5));
        System.out.println(ceil(Math.PI*100000, 0));
        System.out.println(ceil(Math.PI*100000, -1));
        System.out.println(ceil(Math.PI*100000, -2));
        System.out.println(ceil(Math.PI*100000, -3));
        System.out.println(ceil(Math.PI*100000, -4));
        System.out.println(ceil(Math.PI*100000, -5));
        System.out.println(ceil(-Math.PI*100000, 0));
        System.out.println(ceil(-Math.PI*100000, -1));
        System.out.println(ceil(-Math.PI*100000, -2));
        System.out.println(ceil(-Math.PI*100000, -3));
        System.out.println(ceil(-Math.PI*100000, -4));
        System.out.println(ceil(-Math.PI*100000, -5));

        System.out.println(floor(Math.PI, 1));
        System.out.println(floor(Math.PI, 2));
        System.out.println(floor(Math.PI, 3));
        System.out.println(floor(Math.PI, 4));
        System.out.println(floor(Math.PI, 5));
        System.out.println(floor(-Math.PI, 1));
        System.out.println(floor(-Math.PI, 2));
        System.out.println(floor(-Math.PI, 3));
        System.out.println(floor(-Math.PI, 4));
        System.out.println(floor(-Math.PI, 5));
        System.out.println(floor(Math.PI*100000, 0));
        System.out.println(floor(Math.PI*100000, -1));
        System.out.println(floor(Math.PI*100000, -2));
        System.out.println(floor(Math.PI*100000, -3));
        System.out.println(floor(Math.PI*100000, -4));
        System.out.println(floor(Math.PI*100000, -5));
        System.out.println(floor(-Math.PI*100000, 0));
        System.out.println(floor(-Math.PI*100000, -1));
        System.out.println(floor(-Math.PI*100000, -2));
        System.out.println(floor(-Math.PI*100000, -3));
        System.out.println(floor(-Math.PI*100000, -4));
        System.out.println(floor(-Math.PI*100000, -5));

        System.out.println(round(Math.PI, 1));
        System.out.println(round(Math.PI, 2));
        System.out.println(round(Math.PI, 3));
        System.out.println(round(Math.PI, 4));
        System.out.println(round(Math.PI, 5));
        System.out.println(round(-Math.PI, 1));
        System.out.println(round(-Math.PI, 2));
        System.out.println(round(-Math.PI, 3));
        System.out.println(round(-Math.PI, 4));
        System.out.println(round(-Math.PI, 5));
        System.out.println(round(Math.PI*100000, 0));
        System.out.println(round(Math.PI*100000, -1));
        System.out.println(round(Math.PI*100000, -2));
        System.out.println(round(Math.PI*100000, -3));
        System.out.println(round(Math.PI*100000, -4));
        System.out.println(round(Math.PI*100000, -5));
        System.out.println(round(-Math.PI*100000, 0));
        System.out.println(round(-Math.PI*100000, -1));
        System.out.println(round(-Math.PI*100000, -2));
        System.out.println(round(-Math.PI*100000, -3));
        System.out.println(round(-Math.PI*100000, -4));
        System.out.println(round(-Math.PI*100000, -5));

        System.out.println(Math.round(-Math.PI*100));
        System.out.println(Math.round((Math.PI*100000000000L)*100000000000000L));
        System.out.println("Math.round(-1.5) is " + Math.round(-1.5));
        System.out.println("Math.round(-2.5) is " + Math.round(-2.5));
        System.out.println("Math.round(-3.5) is " + Math.round(-3.5));
        System.out.println("Math.round(-4.5) is " + Math.round(-4.5));
        System.out.println("Math.round(-5.5) is " + Math.round(-5.5));
        System.out.println("Math.round(-6.5) is " + Math.round(-6.5));
        System.out.println("Math.round(-7.5) is " + Math.round(-7.5));
        System.out.println("Math.round(-8.5) is " + Math.round(-8.5));
        System.out.println("Math.round(-9.5) is " + Math.round(-9.5));
    }

    private static double[] lowUnits = { 1.0, 1.0E-1, 1.0E-2, 1.0E-3, 1.0E-4, 1.0E-5, 1.0E-6, 1.0E-7, 1.0E-8,
                                         1.0E-9, 1.0E-10, 1.0E-11, 1.0E-12, 1.0E-13, 1.0E-14, 1.0E-15, 1.0E-16 };

    private static double[] highUnits = { 1.0, 1.0E1, 1.0E2, 1.0E3, 1.0E4, 1.0E5, 1.0E6, 1.0E7, 1.0E8,
                                          1.0E9, 1.0E10, 1.0E11, 1.0E12, 1.0E13, 1.0E14, 1.0E15, 1.0E16 };


    ///////////////////////////////////////////////////////
    // 절삭(truncate) 메소드
    // @param data   입력 데이터. double 타입.
    // @param pos    절삭될 위치. int 타입
    // @return       절삭된 결과. double 타입.
    public static double truncate(double data, int pos) {
        if (pos == 0)
            return Math.floor(data);
        else if (pos > 0 && pos <= highUnits.length)
            return lowUnits[pos] * Math.floor(data * highUnits[pos]);
        else if (pos < 0 && pos >= -lowUnits.length)
            return highUnits[-pos] * Math.floor(data * lowUnits[-pos]);
        else
            throw new RuntimeException(data + " cannot be truncated at the position " + pos);
    }


    ///////////////////////////////////////////////////////
    // 잘라내림(floor) 메소드
    // @param data   입력 데이터. double 타입.
    // @param pos    잘라내릴 위치. int 타입
    // @return       잘라내린 결과. double 타입.
    public static double floor(double data, int pos) {
        if (data >= 0.0) {
            if (pos == 0)
                return Math.floor(data);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * Math.floor(data * highUnits[pos]);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * Math.floor(data * lowUnits[-pos]);
            else
                throw new RuntimeException(data + " cannot be floored at the position " + pos);
        }
        else {
            if (pos == 0)
                return -Math.ceil(-data);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * -Math.ceil(-data * highUnits[pos]);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * -Math.ceil(-data * lowUnits[-pos]);
            else
                throw new RuntimeException(data + " cannot be truncated at the position " + pos);
        }
    }

    ///////////////////////////////////////////////////////
    // 잘라올림(ceil) 메소드
    // @param data   입력 데이터. double 타입.
    // @param pos    잘라올릴 위치. int 타입
    // @return       잘라올린 결과. double 타입.
    public static double ceil(double data, int pos) {
        if (data >= 0.0) {
            if (pos == 0)
                return Math.ceil(data);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * Math.ceil(data * highUnits[pos]);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * Math.ceil(data * lowUnits[-pos]);
            else
                throw new RuntimeException(data + " cannot be ceiled at the position " + pos);
        }
        else {
            if (pos == 0)
                return -Math.floor(-data);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * -Math.floor(-data * highUnits[pos]);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * -Math.floor(-data * lowUnits[-pos]);
            else
                throw new RuntimeException(data + " cannot be floored at the position " + pos);
        }
    }

    ///////////////////////////////////////////////////////
    // 반올림(round) 메소드
    // @param data   입력 데이터. double 타입.
    // @param pos    반올림할 위치. int 타입
    // @return       반올림된 결과. double 타입.
    public static double round(double data, int pos) {
        if (data >= 0.0) {
            if (pos == 0)
                return Math.floor(data + 0.5);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * Math.floor(data * highUnits[pos] + 0.5);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * Math.floor(data * lowUnits[-pos] + 0.5);
            else
                throw new RuntimeException(data + " cannot be floored at the position " + pos);
        }
        else {
            if (pos == 0)
                return -Math.floor(-data + 0.5);
            else if (pos > 0 && pos <= highUnits.length)
                return lowUnits[pos] * -Math.floor(-data * highUnits[pos] + 0.5);
            else if (pos < 0 && pos >= -lowUnits.length)
                return highUnits[-pos] * -Math.floor(-data * lowUnits[-pos] + 0.5);
            else
                throw new RuntimeException(data + " cannot be truncated at the position " + pos);
        }
    }


    public static void main(String[] args) {
        TruncateTest app = new TruncateTest();
        app.doTest();
    }
}


실행 결과
===================================
3.1
3.14
3.141
3.1415
3.1415900000000003
-3.2
-3.15
-3.142
-3.1416
-3.1416000000000004
314159.0
314150.0
314100.0
314000.0
310000.0
300000.0
-314160.0
-314160.0
-314200.0
-315000.0
-320000.0
-400000.0
3.2
3.15
3.142
3.1416
3.1416000000000004
-3.1
-3.14
-3.141
-3.1415
-3.1415900000000003
314160.0
314160.0
314200.0
315000.0
320000.0
400000.0
-314159.0
-314150.0
-314100.0
-314000.0
-310000.0
-300000.0
3.1
3.14
3.141
3.1415
3.1415900000000003
-3.2
-3.15
-3.142
-3.1416
-3.1416000000000004
314159.0
314150.0
314100.0
314000.0
310000.0
300000.0
-314160.0
-314160.0
-314200.0
-315000.0
-320000.0
-400000.0
3.1
3.14
3.142
3.1416
3.1415900000000003
-3.1
-3.14
-3.142
-3.1416
-3.1415900000000003
314159.0
314160.0
314200.0
314000.0
310000.0
300000.0
-314159.0
-314160.0
-314200.0
-314000.0
-310000.0
-300000.0
-314
9223372036854775807
Math.round(-1.5) is -1
Math.round(-2.5) is -2
Math.round(-3.5) is -3
Math.round(-4.5) is -4
Math.round(-5.5) is -5
Math.round(-6.5) is -6
Math.round(-7.5) is -7
Math.round(-8.5) is -8
Math.round(-9.5) is -9



7.대문자 -> 소문자, 소문자 -> 대문자



코드
===================================
String upper = "ABCDEFG";
String lower = upper.toLowerCase();
System.out.println(lower);


결과
===================================
abcdefg


보너스 하나더 (소문자 >> 대문자 )
===================================
String lower = "abcdefg";
String upper = lower.toUpperCase();
System.out.println(upper);



8.E-Mail 주소 Check



System.out.println(isValidEmailAddress("vivianchow.mailinglist.admin@hk.net.com"));
System.out.println(isValidEmailAddress("vivianchow.mailinglist.admin@hk.net.co@m"));

public static boolean isValidEmailAddress(String address) {
    return Pattern.matches("^[a-z0-9-_.]+\\@\\[?[a-z0-9-_]+(?:\\.[a-z0-9-_]+){1,4}\\[?$", address);
}

결과
===================================
true
false



9.데이터 구조



// 자바는 객체지향 언어입니다.
// 다음은 객체 개념의 잇점을 이용하여 친구 관계를 구성해 보았습니다.

import java.util.*;

public class FriendInfoTest {
    class FriendInfo {
        private String name = null;
        private String relation = null;
        private Hashtable friends = new Hashtable();
        public FriendInfo(String name, String relation) {
            this.name = name;
            this.relation = relation;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getRelation() {
            return relation;
        }
        public void setRelation(String relation) {
            this.relation = relation;
        }
        public Enumeration getFriends() {
            return friends.keys();
        }
        public void addFriend(FriendInfo info) {
            friends.put(info.getName(), info);
        }
        public FriendInfo getFriend(String name) {
            return (FriendInfo) friends.get(name);
        }
        public String toString() {
            return name;
        }
        public String whoIs() {
            return relation;
        }
    }

    public void doTest() {
        FriendInfo accplus = new FriendInfo("김선달", "본인");
        FriendInfo shakalis = new FriendInfo("달님이", "선달이의 여자 친구");
        FriendInfo circuit = new FriendInfo("홍길동", "김선달의 학교 선배");
        accplus.addFriend(shakalis);
        accplus.addFriend(circuit);
        shakalis.addFriend(accplus);
        circuit.addFriend(accplus);
        System.out.println(accplus + ": " + accplus.whoIs());

        Enumeration keys = accplus.getFriends();
        String str = null;
        while (keys.hasMoreElements()) {
            str = (String) keys.nextElement();
            System.out.println("    " + str + " ==> " + accplus.getFriend(str).whoIs());
        }
    }

    public static void main(String[] args) {
        FriendInfoTest app = new FriendInfoTest();
        app.doTest();
    }
}

실행 결과:
====================================
김선달: 본인
    홍길동 ==> 김선달의 학교 선배
    달님이 ==> 선달이의 여자 친구



10.Date & Time 출력



SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 M월 d일 (E) HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일 (E) a hh:mm:ss SSS");

//
Date date = new Date();
System.out.println(date);
System.out.println(sdf.format(date));
System.out.println(sdf2.format(date));

// 또는
Date date2 = new Date(103, 7, 15, 13, 30);
System.out.println(date2);
System.out.println(sdf.format(date2));
System.out.println(sdf2.format(date2));

// 또는
Calendar now = new GregorianCalendar();
System.out.println(now.get(Calendar.YEAR) + "년 "+ (now.get(Calendar.MONTH) + 1) + "월 " + now.get(Calendar.DAY_OF_MONTH) + "일");

// 또는
Calendar cal = new GregorianCalendar(2003, 7, 15, 13, 30);
System.out.println(cal.get(Calendar.YEAR) + "년 "+ (cal.get(Calendar.MONTH) + 1) + "월 " + cal.get(Calendar.DAY_OF_MONTH) + "일");
System.out.println(sdf.format(cal.getTime()));
System.out.println(sdf2.format(cal.getTime()));


출처:http://www.javaclue.org:8080/tbbs/view?board=doc&pg=1&num=143

글쓴이:자바클루--MORE----MORE--

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

[JSP] Session  (0) 2006.12.05
오라클 9i에서 테이블명및 컬럼명 변경방법  (0) 2006.04.24
사용자 접근 권한 - GRANT, REVOKE  (0) 2006.04.24

+ Recent posts