2013. 7. 25. 16:40


public class Ex77_Recursive {
    public static void main(String[] args) {
 
        //팩토리얼
        //4! = 4 x 3 x 2 x 1 = 24
        //4! = 4 x 3 x 2! = 24
        //4! = 4 x 3! = 24
        //4! = 4! = 24
         
        int result = factorial(4);
        System.out.println(result); 
    }
 
    public static int factorial(int n){
 
        if (n>1)
            return n * factorial(n-1); //재귀호출
        else
            return 1;
    }
}


'java' 카테고리의 다른 글

Generic, 제네릭  (0) 2013.07.25
상속과 구현, 업캐스팅  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
제어문  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:38

Args, arguments

 : 비정형 인자

 : 매개변수를 배열로 변환하는 키워드



1
2
3
4
5
public void showArgs(int... args)
{
    System.out.println(args[0]);
    System.out.println(args[1]);
}


전달받은 int형 인자값을 args[]배열에 저장하여 배열의 요소를 출력하는 메서드다.

단 이렇게 코드를 작성하면 인자값이 2개가 아닐때 에러가 발생한다. (ArrayIndexOutOfBoundsException)


따라서 런타임 에러를 방지하기 위해선 다음처럼 작성한다.


1
2
3
4
5
6
7
8
public void showArgs(int... args)
{
    for(int i=0; i<args.length; i++)
     //전달받은 인자값만큼 배열의 길이가 결정되므로 그 만큼만 반복
    {
        System.out.println(args[i]);
    }
}

향상된 포문을 활용할 경우 다음과 같다.


1
2
3
4
5
6
7
public void showArgs(int... args)
{
    for(int ns : args)
    {
        System.out.println(ns);
    }
}



다음 예제는 args를 활용한 인자값들의 계산 결과를 구하는 메서드다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Args
{
    public int multiply(int... args)
    {
        int result=1;
         
        for(int ns : args)
        {
            result = result * ns;
        }
         
        return result;
    }
}
 
 
Args a = new Args();
System.out.println(a.multiply(2, 2, 2, 2));
16


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
    m1(1, 2, 3); //6
    m1(1, 2, 3, 4); //10
}
     
public static int m1(int... args) {
    int sum = 0;
     
    for(int i=0; i<args.length; i++)
    {
        sum += args[i];
    }
    return sum;
}


'java' 카테고리의 다른 글

상속과 구현, 업캐스팅  (0) 2013.07.25
팩토리얼(재귀호출)  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
제어문  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:36

System.out.println("ㅇㅇ" instanceof String);  //인스턴스의 클래스를 확인하는 연산자, 불리언을 리턴함

'java' 카테고리의 다른 글

팩토리얼(재귀호출)  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
제어문  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:34

제어문

 : 프로그램의 코드 실행 흐름을 제어하는 구문(위->아래)

 : 조건, 반복, 분기 등을 통해 흐름을 제어

 

■ 조건문 : if, switch

■ 반복문 : for, 향상된for, while, dowhile

■ 분기문 : continue, break, goto

 

● if

 : 조건을 제시한 뒤 만족하거나 불만족할 때의 코드를 분기하는 제어문

 : 조건은 반드시 boolean

 : if~elseif~else 구간 중 만족하는 조건이 있다면 블럭을 실행하고 if문을 끝낸다.

 : if문은 중첩으로 사용 가능하다 : 제어문 중첩

if(조건식)

{

    ~~

if(조건식) 

              ~~

} else 

              ~~

} else if(조건식)

{

     ~~

} else 

{

     ~~

}

 

 

● switch

 : switch case문, 조건 1개를 갖고 제어를 분기

switch (조건값)

{

case 값1:  // label

실행문;

break;

case 값2:  

실행문;

break;

default: // else와 같다.

실행문;

break;      

}

 

switch (조건값)

{

case 값1

case 값2:

실행문;

break;

}    // 값1, 값2 둘다 같은 블럭을 실행한다. (break가 없어서 가능한 경우)

 

● for

 : 특정 실행 코드 블럭을 원하는 횟수만큼 반복 제어

for(초기식; 조건식; 증감식;) 

{

실행문;

 

● 향상된 for문

for (variable ele : locationEle) {}  //locationEle : 배열 또는 컬렉션

 

 

1
2
3
4
5
6
7
int[] n = new int[] {40,20,10,50,30,60,35,41,23,78} ;
 
for (int i : n) {
    System.out.println(i);
 
//n의 배열 길이만큼 루프를 돌되 각 사이클마다 i에 객체주소를 저장

 

 

다음처럼 배열을 직접 선언하여 사용하기도 한다.

 

 

1
for (String i : new String[] { "+", "-", "*", "/" })

 

 

 

● while

 

 

1
2
3
4
5
6
int n=1; //초기식
while (n < 11) //조건식
{
    System.out.println(n);
    ++n; //증감식
}

 

 

 

● do while

 

 

1
2
3
4
5
6
7
int n = 1;
do
{
    System.out.println(n);
    ++n;
}
while (n<=10); //선실행 후에 조건식을 참조하기 때문에 조건식이 false라도 일단 실행문은 처리된다.

 

 

 

● continue, break

 break : 현재 자신이 속한 제어문을 탈출

 

 

1
2
3
4
5
6
7
8
for(int i=1; i<11; i++)
{
    if(i==5)
    {
        break
    }
    System.out.println(i);
}   //1,2,3,4

 

 

 continue : 현재 자신이 속한 제어문(if문X) 처음으로 되돌아감

 

 

1
2
3
4
5
6
7
8
for(int i=1; i<11; i++)
{
    if(i==5)
    {
        continue
    }
    System.out.println(i);
}   //1,2,3,4,6,7,8,9,10

 

 

 이름 있는 반복문에서 continue

 

 

1
2
3
4
5
6
7
8
9
10
11
loop: for(int i=0; i<10; i++)
{
    System.out.println("x = " + i);
    for(int j=0; j<10; j++)
    {
        System.out.println("j = " + j);
        if(j>=5)
            continue loop; //loop란 이름을 붙인 for문으로 continue
                                                    //break와 성격이 겹치기 때문에 잘 쓰이진 않음.
    }
}

 

 

'java' 카테고리의 다른 글

Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
피보나치  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:31


private static void m001() {
    // 문제1. 파일명을 아래와 같이 변경하시오.
    // 보기] aaa.txt
    // bbb.txt
    // 안녕.hwp
    // hello.java
    // 실행]
    // 결과] [01]aaa.txt
    // [02]bbb.txt
    // [03]안녕.hwp
    // [04]hello.java
    // 코드] renameTo : 파일명바꾸기
    // aaa.txt -> [01]aaa.txt
    // 조건] 해당 폴더 파일의 갯수가 10개 미만이면 숫자를 1자리
    // 해당 폴더 파일의 갯수가 100개 미만이면 숫자를 2자리
    // 해당 폴더 파일의 갯수가 1000개 미만이면 숫자를 3자리
 
    File dir = new File("D:\\temp\\AAA"); // 작업경로 지정
    String path = dir.getPath(); // dir의 경로 문자열
    File[] list = dir.listFiles(); // dir의 배열 list선언
 
    int fileCnt = 0; // 카운터
 
    for (File i : list) {
        if (i.isFile())
            fileCnt++; // file/folder 필터링
    }
 
    int totalLen = (fileCnt + "").length(); // (변경할 파일의 총 갯수)의 자릿수
    fileCnt = 0;
 
    for (int i = 0; i < list.length; ++i) { // i=0 ~ dir 구성원의 갯수만큼
        String reName = path + "\\[";
        if (list[i].isFile()) { // 파일일 경우에만
            fileCnt++;
            int cntLen = (fileCnt + "").length();
            if (cntLen < totalLen) {
                for (int j = cntLen; j < totalLen; ++j) {
                    reName += "0";
                }
            }
            reName += fileCnt + "]" + list[i].getName();
            System.out.println(reName);
        }
    }
}


아래가 더 간단함


private static void m002() {
    String path = "D:\\temp"; // dir의 경로 문자열
    File dir = new File(path); // 작업경로 지정
    File[] list = dir.listFiles(); // dir의 배열 list선언
 
    int fileCnt = 0; // 카운터
 
    for (File i : list) {
        if (i.isFile())
            fileCnt++; // file/folder 필터링
    }
 
    int totalLen = (fileCnt + "").length(); // (변경할 파일의 총 갯수)의 자릿수
    fileCnt = 0;
 
    for (int i = 0; i < list.length; ++i) {
        if (list[i].isFile()) {
            String txt1 = String.format("\\\\[%%0%dd]", totalLen);
            String txt2 = String.format(txt1, ++fileCnt);
            File dest = new File(path + txt2 + list[i].getName());
 
            System.out.println(dest.getAbsolutePath());
        }
    }
}


'java' 카테고리의 다른 글

연산자 우선순위  (0) 2013.07.25
제어문  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
피보나치  (0) 2013.07.25
로또생성기  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:31


public static void main(String[] args) throws IOException {
 
    // BufferedReader reader = new BufferedReader(new
    // FileReader("data\\directory.txt"));
    // String dir = reader.readLine();
    // reader.close();
    String dir = "D:\\Documents";
 
    getResult(dir);
    System.out.printf("크기%,d, 파일%,d개, 폴더%,d\n", sizeSum, fileCnt, folderCnt);
}
 
static int fileCnt = 0, folderCnt = 0;
static long sizeSum = 0;
 
private static void getResult(String directory) // static 멤버 변수에 값 누적
{
    File dir = new File(directory);
    File[] list = dir.listFiles();
 
    for (File i : list) { // 현재경로의 폴더, 파일 갯수 합산
        if (i.isDirectory()) {
            getResult((i.getAbsoluteFile()) + ""); // 중단하고 발견한 폴더에서 재탐색
            folderCnt++;
        } else if (i.isFile()) {
            fileCnt++;
            sizeSum += i.length();
        }
    }
}
 
 
크기11,139,473, 파일35개, 폴더5


'java' 카테고리의 다른 글

제어문  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
피보나치  (0) 2013.07.25
로또생성기  (0) 2013.07.25
세로형 성적 그래프  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:30


public static void main(String[] args) {
    int a = 0, b = 0, c = 1;
 
    int sum = 1;
    System.out.print("1 + ");
 
    for (;;) {
        a = b;
        b = c;
        c = a + b;
 
        sum += c;
 
        System.out.printf("%d + ", c);
 
        if (c == 34) {
            System.out.printf("\b\b= %d", sum);
            break;
        }
    }
}
 
 
1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 88


'java' 카테고리의 다른 글

파일명 일괄변경  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
로또생성기  (0) 2013.07.25
세로형 성적 그래프  (0) 2013.07.25
Callendar 클래스 없이 달력만들기  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:30



'java' 카테고리의 다른 글

폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
피보나치  (0) 2013.07.25
세로형 성적 그래프  (0) 2013.07.25
Callendar 클래스 없이 달력만들기  (0) 2013.07.25
숫자를 한글로 변환(금액단위)  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:29



'java' 카테고리의 다른 글

피보나치  (0) 2013.07.25
로또생성기  (0) 2013.07.25
Callendar 클래스 없이 달력만들기  (0) 2013.07.25
숫자를 한글로 변환(금액단위)  (0) 2013.07.25
검색어 발견 카운터  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:28



'java' 카테고리의 다른 글

로또생성기  (0) 2013.07.25
세로형 성적 그래프  (0) 2013.07.25
숫자를 한글로 변환(금액단위)  (0) 2013.07.25
검색어 발견 카운터  (0) 2013.07.25
빼기연산으로 몫과 나머지 구하기  (0) 2013.07.25
Posted by 1+1은?