카테고리 보관물: java

Java 별찍기

프로그래밍을 배우다 보면 반복문에서 주로 연습하는게 별찍기 입니다. 별찍기를 이해 하면
반복문을 거의 이해 했다고 생각됩니다. 지식인에 올릴려고 했지만 다른 사람이 이미 답변을 달아서…

package quiz;

public class AsteriskQuiz {
    public static char printChar = '*';

    public static void main(String[] args) {
        int count = 5;
        System.out.println("--------1번 삼각형-------");
        /*
         *  *
            **
            ***
            ****
            *****
         */
        for(int i=0; i<count; i++) {
            for(int j=0;j<=i;j++) {
                System.out.print(printChar);
            }
            System.out.println();
        }



        System.out.println("---------2번 삼각형--------");



        /*
         *       *
                **
               ***
              ****
             *****
         */
        for(int i=0; i<count; i++) {
            for(int j= count-i; j > 0;j--) {
                System.out.print(" ");
            }
            for(int k=0; k<=i; k++) {
                System.out.print(printChar);
            }
            System.out.println();
        }



        System.out.println("--------3번 삼각형 --------");



        /*
         *       *
                ***
               *****
              *******
             *********
         */
        for(int i=0; i<count; i++) {
            for(int j=count-i; j>0; j--) {
                System.out.print(" ");
            }
            for(int k=0; k< (i*2)+1; k++) {
                System.out.print(printChar);
            }
            System.out.println();
        }



        System.out.println("--------1번 사각형 ----------");
        /*
         *  *****
            *   *
            *   *
            *   *
            *****
         */
        for(int i=0; i<count; i++) {
            for(int j=0; j<count; j++) {
                if(
                        i== 0 
                        || i == count-1
                        || j == 0 
                        || j == count-1) {
                    System.out.print(printChar);
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }







        System.out.println("-------- 꽉찬 사각형 ----------");
        /*
         *  *****
            *****
            *****
            *****
            *****
         */
        for(int i=0;i < count; i++) {
            for(int j=0; j <count; j++) {
                System.out.print(printChar);
            }
            System.out.println();
        }

        System.out.println("------- 삼각형 + 사각형--------");
        /*
         *       *
                ***
               *****
            **********
            **********
            **********
            **********
         */
        for(int i=0; i<3; i++) {
            for(int j=5-i; j>0; j--) {
                System.out.print(" ");
            }
            for(int k=0; k< (i*2)+1; k++) {
                System.out.print(printChar);
            }
            System.out.println();
        }
        for(int i=0;i < 4; i++) {
            for(int j=0; j <10; j++) {
                System.out.print(printChar);
            }
            System.out.println();
        }

    }
}

자바 List,ArrayList,소트에대해 질문드립니다.

Question:

안녕하세요. 17살부터 자바웹프로그래머를꿈꾸고온 18살 홍승민이라합니다.

다만 제가지금 자바공부를하면서 List종류에막혔거든요.

그래서 질문드립니다. 답장꼭해주세요ㅠ.ㅠ

1.

List list = new ArrayList(); 와

ArrayList list = new ArrayList(); 는 뭐가 다른것인가요?

2.

List list = new ArrayList(); 와

List list = new ArrayList(); 는 뭐가다른것인가요?

  1. 소스질문드립니다.

성적관리 프로그램을 만들고 있는데 소트에서 막혔습니다.

총점에따라 성적을 나누려고하는데요.

이름 국어 영어 총점

홍 100 10 110

승 100 90 190

민 100 100 200

로 입력한다면

이름 국어 영어 총점

민 100 100 200

승 100 90 190

홍 100 10 110

이렇게 소트하고싶은데, 도저희 어디서부터 소트를해야하며 어디서부터 소트를만들어야하는지 모르겠습니다.

class Student
{
    String name;
    double total;
    double avg;
    double[] score;
    public Student(String name,double[] score)
    {
        this.name = name;
        this.score = score;
    }
    public void list()
    {
        calculateTotal();
        calculateAverage();
        System.out.print(name+"t");
    for(int x = 0;x < score.length;x++)
    {
        System.out.print(score[x]+"t");
    }
    System.out.print(total+"t");
    System.out.print(avg);

    }
    public void calculateTotal()
    {
        for(int x = 0;x < score.length;x++)
        {
            total += score[x];
        }
    }
    public void calculateAverage()
    {
        avg = total/score.length;
    }

}

import java.io.*;
import java.util.*;

public class Exam_01
{
public static void main(String[] ar) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ArrayList list = new ArrayList();
System.out.print("과목 겟수 :: ");
int sub = Integer.parseInt(in.readLine());
String[] subject = new String[sub];

for(int x = 0;x < subject.length;x++)
{
System.out.print(x+1+"번 과목의 이름 :: ");
String s = in.readLine().toString();
subject[x] = s;
}
System.out.print("학생 수 :: ");
int stu = Integer.parseInt(in.readLine());
int i = 0;
for(int x = 0;x < stu;x++)
{
System.out.print(x+1+"번 학생의 이름 :: ");
String name = in.readLine().toString();
double[] sco = new double[sub];
for(int z = 0;z < subject.length;z++)
{
boolean test = false;
while(!test)
{
System.out.print(subject[z]+" 과목의 점수 :: ");
double score = Double.parseDouble(in.readLine());
if(score 100)
{
System.out.println("0보다작거나 100보다 큽니다. 다시입력해주세요.");
test = false;
}
else
{
sco[x] = score;
test = true;
}
}
}
Student data = new Student(name,sco);
list.add(data);
}
System.out.print("이름"+"t");
for(int y = 0; y < subject.length;y++)
{
System.out.print(subject[y]+"t");
}
System.out.print("총점t평균");
System.out.println();
for(int x = 0;x < stu;x++)
{
Student target = (Student)list.get(x);
target.list();
System.out.println();
}
}
}

입니다.

무엇을서야하며 어디서 고쳐야하는지 , 답을 알려주시면 감사드리겠습니다.

부탁드립니다

Answer:

1.

List list = new ArrayList(); 와

ArrayList list = new ArrayList(); 는 뭐가 다른것인가요?

간단하게 예를 들어 설명하도록 하겠습니다.

List list = new ArrayList() 는

도형 list = new 정사각형();

ArrayList list = new ArrayList();

정사각형 list = new 정사각형();

위의 예처럼 List는 interface입니다. 인터페이스는 공통되는 메소드를 추출해놓은 클래스로 생각하시면 됩니다. 클래스를 생성할때 도형 타입으로 생성하게 되면 정사각형이 아닌 다른 직사각형, 삼각형등 도형 인터페이스를 구현한 클래스에서 사용 될 수 있습니다. 그렇지만 정사각형 클래스로 생성하게 되면 직사각형, 삼각형등에서는 사용할 수 없게 됩니다. 자바의 특징중 다형성을 참조 하십시오.

2.

List list = new ArrayList(); 와

List list = new ArrayList(); 는 뭐가다른것인가요

이 부분은 위와 비슷한 부분인데 간단하게 List에 담겨질 객체의 타입을 정해 준 겁니다. 기본적으로 자바의 Collection 은 Object 타입으로 추가가 됩니다.

List list = new ArrayList();

Object obj = list.get(1); // 이런식으로 Object 타입으로 리턴이 됩니다.

그렇지만

List list = new ArrayList<Student)();

Student stu = list.get(1); // 이런식으로 return 타입이 Student 객체로 출력 됩니다.

그리고 타입을 설정하게 되면 Student 객체가 아닌 다른 타입은 add를 할 수 없기 때문에

오류를 예방 할 수 있습니다.

  1. 코드 수정 및 정렬
    저는 BufferedInputStream이 아닌 Scanner를 사용해서 작성했습니다.

형변환을 피하기 위해서 변경 해봤습니다. 붉게 표시된 부분이 질문자님의 코드와

다른 부분입니다.

  • score[x] = score 로 사용하셨는데 x변수는 학생 수를 의미 하므로 z로 변경 해주셔야 합니다.

  • Collections.sort(list, new StudentComparator());

이 부분은 리스트를 정렬하기 위해 사용합니다. 뒤에 있는 StudentComparator() 클래스를 정렬할 기준을

정해주기 위해 사용했습니다.

예를 들어

int a = 0;

int b = 1;

위와 같이 정수형 변수 a,b 에서는 어떤것이 크고 작다를 알 수 있습니다.

그렇지만 Student 클래스 a,b 를 비교하기 위해서 기준을 알 수 없습니다. 국어 과목을 기준으로 정렬할 것인지 수학을 기준으로 정렬할 것인지 총점으로 정렬할 것인지…

그래서 기준을 정의 하기 위해 작성했습니다.

package sort;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Exam_01 {

    public static void main(String[] ar) throws IOException {
        Scanner scanner = new Scanner(System.in, "euc-kr");
//        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        ArrayList list = new ArrayList();

        System.out.print("과목 겟수 :: ");
        int sub = scanner.nextInt();
//        int sub = Integer.parseInt(in.readLine());
        String[] subject = new String[sub];

//        for (int x = 0; x < subject.length; x++) {
//            System.out.print(x + 1 + "번 과목의 이름 :: ");
//            String s = in.readLine().toString();
//            subject[x] = s;
//        }
        System.out.println("과목명을 입력하세요.");

        for(int i=0; i<sub; i++) {
            subject[i] = scanner.next();
        }



        System.out.print("학생 수 :: ");
//        int stu = Integer.parseInt(in.readLine());
        int stu = scanner.nextInt();
        int i = 0;
        for (int x = 0; x < stu; x++) {
            System.out.print(x + 1 + "번 학생의 이름 :: ");
//            String name = in.readLine().toString();
            String name = scanner.next();
            double[] sco = new double[sub];
            for (int z = 0; z < subject.length; z++) {
                boolean test = false;
                while (!test) {
                    System.out.print(subject[z] + " 과목의 점수 :: ");
//                    double score = Double.parseDouble(in.readLine());
                    double score = scanner.nextDouble();
                    if (score  100) {
                        System.out.println("0보다작거나 100보다 큽니다. 다시입력해주세요.");
                        test = false;
                    } else {
                        sco[z] = score; // x는 학생 수 이므로 z로 변경 필요
                        test = true;
                    }
                }
            }
            Student data = new Student(name, sco);
            list.add(data);
        }

        System.out.print("이름" + "t");
        for (int y = 0; y < subject.length; y++) {
            System.out.print(subject[y] + "t");
        }
        Collections.sort(list, new StudentComparator());

        System.out.print("총점t평균");
        System.out.println();


        for (int x = 0; x < stu; x++) {
            Student target = (Student) list.get(x);
            target.list();
            System.out.println();
        }
    }
}

class Student {

    String name;
    double total;
    double avg;
    double[] score;

    public Student(String name, double[] score) {
        this.name = name;
        this.score = score;
    }

    public void list() {
        calculateTotal();
        calculateAverage();


        System.out.print(name + "t");
        for (int x = 0; x < score.length; x++) {
            System.out.print(score[x] + "t");
        }
        System.out.print(total + "t");
        System.out.print(avg);



    }

    public void calculateTotal() {
        for (int x = 0; x < score.length; x++) {
            total += score[x];
        }
    }

    public void calculateAverage() {
        avg = total / score.length;
    }
}


/**
 * Student 클래스를 비교 하기 위한 비교 조건
 */
class StudentComparator implements Comparator {

    @Override
    public int compare(Student student1, Student student2) {
        // 총점이 높은 사람을 조건으로 하여 정렬하도록 합니다.
        if(student1.total >= student2.total) {
            return 1;
        } else {
            return 0;
        }

    }

}

Buffered I/O 클래스를 이용한 파일 I/O 시의 효율성 측정-2

Buffered I/O 클래스를 이용한 파일 I/O 시의 효율성 측정-1

측정한 결과가 한번만 실행한 결과를 표현하는 방법은 아니라는 생각에 10회를 반복한 결과를 첨부합니다.
실행환경:
프로세서: Inter Core2 Duo CPU P8700 2.53
메모리 : 4G
운영체제: Window 7 64Bit
자바 버전: 1.6.0_26
개발툴 : 이클립스 헬리오스
테스트파일 : 100Mbyte

Result:

DataInputStream[1024] takes 1077 ms
BufferedInputStream[1024] takes 378 ms
InputStream[1024] takes 1020 ms

DataInputStream[2048] takes 628 ms
BufferedInputStream[2048] takes 376 ms
InputStream[2048] takes 810 ms

DataInputStream[4096] takes 692 ms
BufferedInputStream[4096] takes 365 ms
InputStream[4096] takes 520 ms

DataInputStream[8192] takes 347 ms
BufferedInputStream[8192] takes 520 ms
InputStream[8192] takes 354 ms

파일 복사 시간은 DataInputStream 과 InputStream 이 비슷하게 나왔습니다.
가장 좋은 성능을 보인것은 BufferedInputStream 입니다. 그렇지만 버퍼 사이즈를 증가 시키면 성능이
저하되는 부분이 있었습니다.

Data:
                 Data    Buffer    Input
BufferSize=1024    938    360    921   
BufferSize=2048    587    318    572   
BufferSize=3072    383    468    389   
BufferSize=4096    275    287    276   

BufferSize=1024    927    319    921   
BufferSize=2048    606    316    885   
BufferSize=3072    382    316    391   
BufferSize=4096    282    806    316   

BufferSize=1024    1000    360    909   
BufferSize=2048    624    351    651   
BufferSize=3072    2626    324    388   
BufferSize=4096    299    816    370   

BufferSize=1024    1075    348    1334   
BufferSize=2048    597    345    1000   
BufferSize=3072    428    341    409   
BufferSize=4096    299    1008    301   

BufferSize=1024    972    340    1033   
BufferSize=2048    622    337    1161   
BufferSize=3072    412    334    412   
BufferSize=4096    664    311    301   

BufferSize=1024    1382    335    936   
BufferSize=2048    609    418    634   
BufferSize=3072    857    387    437   
BufferSize=4096    426    435    452   

BufferSize=1024    1162    523    1061   
BufferSize=2048    746    639    823   
BufferSize=3072    549    367    504   
BufferSize=4096    317    303    643   

BufferSize=1024    959    328    939   
BufferSize=2048    647    339    636   
BufferSize=3072    412    341    691   
BufferSize=4096    318    383    296   

BufferSize=1024    989    396    1096   
BufferSize=2048    655    357    643   
BufferSize=3072    469    437    1165   
BufferSize=4096    305    310    291   

BufferSize=1024    1372    473    1055   
BufferSize=2048    592    348    1096   
BufferSize=3072    404    338    416   
BufferSize=4096    289    543    296   

코드가 지저분해도 이해를 부탁드립니다.

Source:

package com.blogspot.coozplz;

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

 

public class CompareDataNBuffer {

    

    /**

     * DataInputStream 을 사용하여 파일을 복사한경우. 

     */

    public long useDataInputStream(int bufferSize, File f) throws IOException {

        File outFile = new File("d:/"+System.currentTimeMillis()+".zip");

        DataInputStream dis = new DataInputStream(new FileInputStream(f));

        

        // 출력 파일명은 임의로 설정 했습니다.

        DataOutputStream dos = new DataOutputStream(

                new FileOutputStream(outFile));

        int readSize = 0;

        byte[] buffer = new byte[bufferSize];

        long sTime = System.currentTimeMillis();

        

        while ((readSize = dis.read(buffer)) > 0) {

            dos.write(buffer, 0, readSize);

        }

        dos.flush();

        dos.close();

        dis.close();

        outFile.delete();

        return getDuration(sTime);

    }

 

    /**

     * BufferedInputStream 을 사용하여 파일을 복사한경우.

     */

    public long useBufferInputStream(int bufferSize, File f) throws IOException {

        File outFile = new File("d:/"+System.currentTimeMillis()+".zip");

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));

        // 출력 파일명은 임의로 설정 했습니다.

        BufferedOutputStream bos = new BufferedOutputStream(

                new FileOutputStream(outFile));

        

        int readSize = 0;

        byte[] buffer = new byte[bufferSize];

        

        long sTime = System.currentTimeMillis();

        

        while((readSize = bis.read(buffer)) > 0) {

            bos.write(buffer, 0, readSize);

        }

        bos.flush();

        bos.close();

        bis.close();

        outFile.delete();

        return getDuration(sTime);

    }

    

    public long useInputStream(int bufferSize, File f) throws IOException {

        File outFile = new File("d:/"+System.currentTimeMillis()+".zip");

        InputStream is = new FileInputStream(f);

        OutputStream os = new FileOutputStream(outFile);

        long sTime = System.currentTimeMillis();

        int readSize = 0;

        byte[] buffer = new byte[bufferSize];

        while((readSize = is.read(buffer)) > 0) {

            os.write(buffer, 0, readSize);

        }

        os.flush();

//        System.out.println("InputStream["+ bufferSize

//                +"]. It takes " + getDuration(sTime) +" ms.");

        os.close();

        is.close();

        outFile.delete();

        

        return getDuration(sTime);

        

    }

 

    /**

     * 시간을 측정함.

     */

    public long getDuration(long startTime) {

        return System.currentTimeMillis() - startTime;

    }

 

    public static void main(String[] args) throws IOException {

        CompareDataNBuffer compareDataNBuffer = new CompareDataNBuffer();

        // 100Mbyte 파일 

        File f100 = new File("d:/dataFile.zip");

        

        // 500MByte 파일

        File f500 = new File("d:/Tapsonic.zip");

        

        // 초기 버퍼 사이즈 입니다.

        int size = 1024;

        

        int count = 10;

        long[][][] time = new long[count][4][3];

        for (int t = 0; t < count; t++) {

            for (int i = 0, len = 4; i < len; i++) {

//                System.out.println("==> Buffer Size is " + size);

                // DataInputStream을 사용하는 경우 

                 time[t][i][0] = compareDataNBuffer.useDataInputStream(size, f100);

                // BufferedInputStream을 사용하는 경우

                 time[t][i][1] = compareDataNBuffer.useBufferInputStream(size, f100);

                // InputStream 을 사용하는 경우

                 time[t][i][2] = compareDataNBuffer.useInputStream(size, f100);

                size = size * 2;

            }

            size = 1024;

        }

        

        // 반복횟수 10회

        // 버퍼 차이에 따라 4회 1024 2048 4096 8192

        // 방법에 따라 3회  Data Buffer InpuStream

        long d1024 = 0;

        long b1024 = 0;

        long i1024 = 0;

        long d2048 = 0;

        long b2048 = 0;

        long i2048 = 0;

        long d4096 = 0;

        long b4096 = 0;

        long i4096 = 0;

        long d8192 = 0;

        long b8192 = 0;

        long i8192 = 0;

        System.out.println("\t\t\t\t\t   Data\t\tBuffer\t\tInput");

        for(int i=0, len=time.length; i<len; i++) {

            for(int j=0, jLen=time[0].length; j<jLen;j++) {

                System.out.print("BufferSize="+((j+1)*1024)+"\t");

                for(int k=0, kLen=time[0][0].length; k<kLen; k++) {

                    long temp = time[i][j][k];

                    

                    switch (j) {

                    case 0:

                        switch (k) {

                        case 0:

                            d1024 += temp;

                            break;

                        case 1:

                            b1024 += temp;

                            break;

                        case 2:

                            i1024 += temp;

                            break;

                        }

                        

                        break;

 

                    case 1:

                        switch (k) {

                        case 0:

                            d2048 += temp;

                            break;

                        case 1:

                            b2048 += temp;

                            break;

                        case 2:

                            i2048 += temp;

                            break;

                        }

                        

                        break;

                        

                    case 2:

                        switch (k) {

                        case 0:

                            d4096+=temp;

                            break;

                        case 1:

                            b4096+=temp;

                            break;

                        case 2:

                            i4096+=temp;

                            break;

                        }

                        

                        break;

                        

                    case 3:

                        switch (k) {

                        case 0:

                            d8192+= temp;

                            break;

                        case 1:

                            b8192+= temp;

                            break;

                        case 2:

                            i8192+= temp;

                            break;

                        }

                        

                        

                        break;

                        

                    }

                    System.out.print(temp+"\t");

                }

                System.out.println();

            }

            System.out.println();

            

        }

        

        System.out.println("DataInputStream[1024] takes " + (d1024/count) +" ms");

        System.out.println("BufferedInputStream[1024] takes " + (b1024/count) +" ms");

        System.out.println("InputStream[1024] takes " + (i1024/count) +" ms");

        

        System.out.println();

        

        System.out.println("DataInputStream[2048] takes " + (d2048/count)+" ms");

        System.out.println("BufferedInputStream[2048] takes " + (b2048/count)+" ms");

        System.out.println("InputStream[2048] takes " + (i2048/count)+" ms");

   

        System.out.println();

        

        System.out.println("DataInputStream[4096] takes " + (d4096/count)+" ms");

        System.out.println("BufferedInputStream[4096] takes " + (b4096/count)+" ms");

        System.out.println("InputStream[4096] takes " + (i4096/count)+" ms");

        

        System.out.println();

        System.out.println("DataInputStream[8192] takes " + (d8192/count)+" ms");

        System.out.println("BufferedInputStream[8192] takes " + (b8192/count)+" ms");

        System.out.println("InputStream[8192] takes " + (i8192/count)+" ms");

        

        

        

//        size = 1024;

//        System.out.println("File Size is "+f500.length());

//        for(int i = 1, len=4; i<=len; i++) {

//            System.out.println("==> Buffer Size is " + size);

//            // DataInputStream을 사용하는 경우 

//            compareDataNBuffer.useDataInputStream(size, f500);

//            // BufferedInputStream을 사용하는 경우

//            System.out.println();

//            compareDataNBuffer.useBufferInputStream(size, f500);

//            System.out.println();

//            // InputStream 을 사용하는 경우

//            compareDataNBuffer.useInputStream(size, f500);

//            System.out.println();

//            

//            

//            size = size*2;

//        }

    }

 

}


 


이 글은 java 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.

Buffered I/O 클래스를 이용한 파일 I/O 시의 효율성 측정

[출처] http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040201&docId=139547597

 

Question:

1. 주제: Buffered I/O 클래스를 이용한 파일 I/O시의 효율성 측정

2. 내용: 100M 이상의 큰 파일을 DataInputStream으로 읽은 후 DataOutputStream으로 다른 파일로 저장 하였을 경우와 BufferedInputStream으로 읽은 후 BufferedOutputStream으로 다른 파일로 저장 하였을 경우에 대한 시간차이를 구하시오.

3. 조건:

가. Buffered I/O를 사용하였을 경우 Buffer의 크기는 1k, 2k, 4k, 8k로 각각 측정하시오.

나. 반듯이 리눅스 환경에서 프로그래밍을 하여 출력 결과는 핵심부분만 캡쳐 하여 제출하시오.

4. 힌트

– 자바에서 프로그램 실행시간을 구하는 예제

class SystemExample11 {
    public static void main(String args[]) {

        long time1 = System.currentTimeMillis();

        double total = 0.0;

        for (int cnt = 1; cnt < 1000000000; cnt += 2) 
            if (cnt / 2 % 2 == 0)
                total += 1.0 / cnt;
            else
                total -= 1.0 / cnt;

        double pi = total * 4;

        long time2 = System.currentTimeMillis();
        System.out.println("result = " + pi);
        System.out.printf("계산에 %d ms가 소요되었습니다.", time2 - time1);
    }
}

이걸 해야하는데 아무리 해도 모르겠어요 ㅠ

 

Answer:

 

 

100MByte 이상 되는 파일과 500MByte 파일 두가지로 테스트를 진행 했습니다.
실행 환경은 리눅스 환경이 없어 윈도우에서 실행 했습니다. 자바의 특성상 리눅스에서도
소스 그대로 실행 하시면 구동 됩니다.(단지 파일명에만 주의 하십시오)

package com.blogspot.coozplz;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CompareDataNBuffer {

    /**
     * DataInputStream 을 사용하여 파일을 복사한경우. 
     */
    public void useDataInputStream(int bufferSize, File f) throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream(f));

        // 출력 파일명은 임의로 설정 했습니다.
        DataOutputStream dos = new DataOutputStream(
                new FileOutputStream("d:/"+System.currentTimeMillis()+".zip"));
        int readSize = 0;
        byte[] buffer = new byte[bufferSize];
        long sTime = System.currentTimeMillis();

        while ((readSize = dis.read(buffer)) > 0) {
            dos.write(buffer, 0, readSize);
        }
        dos.flush();
        System.out.println("DataInputStream["+ bufferSize+"]" 
                +". It takes " + getDuration(sTime) +" ms.");
        dos.close();
        dis.close();
    }

    /**
     * BufferedInputStream 을 사용하여 파일을 복사한경우.
     */
    public void useBufferInputStream(int bufferSize, File f) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        // 출력 파일명은 임의로 설정 했습니다.
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("d:/"+System.currentTimeMillis()+".zip"));

        int readSize = 0;
        byte[] buffer = new byte[bufferSize];

        long sTime = System.currentTimeMillis();

        while((readSize = bis.read(buffer)) > 0) {
            bos.write(buffer, 0, readSize);
        }
        bos.flush();
        System.out.println("BufferedInputStream["+ bufferSize
                +"]. It takes " + getDuration(sTime) +" ms.");
        bos.close();
        bis.close();
    }

    /**
     * 시간을 측정함.
     */
    public long getDuration(long startTime) {
        return System.currentTimeMillis() - startTime;
    }

    public static void main(String[] args) throws IOException {
        CompareDataNBuffer compareDataNBuffer = new CompareDataNBuffer();
        // 100Mbyte 파일 
        File f100 = new File("d:/dataFile.zip");

        // 500MByte 파일
        File f500 = new File("d:/Tapsonic.zip");


        // 초기 버퍼 사이즈 입니다.
        int size = 1024;
        System.out.println("File Size is "+f100.length());
        for(int i = 1, len=4; i<=len; i++) {
            System.out.println("==> Buffer Size is " + size);
            // DataInputStream을 사용하는 경우 
            compareDataNBuffer.useDataInputStream(size, f100);

            // BufferedInputStream을 사용하는 경우
            compareDataNBuffer.useBufferInputStream(size, f100);
            System.out.println();
            size = size*2;
        }
        size = 1024;
        System.out.println("File Size is "+f500.length());
        for(int i = 1, len=4; i<=len; i++) {
            System.out.println("==> Buffer Size is " + size);
            // DataInputStream을 사용하는 경우 
            compareDataNBuffer.useDataInputStream(size, f500);
            // BufferedInputStream을 사용하는 경우
            compareDataNBuffer.useBufferInputStream(size, f500);
            System.out.println();
            size = size*2;
        }
    }

}

[출력결과]

File Size is 114482881
==> Buffer Size is 1024
DataInputStream[1024]. It takes 1060 ms.
BufferedInputStream[1024]. It takes 375 ms.

==> Buffer Size is 2048
DataInputStream[2048]. It takes 692 ms.
BufferedInputStream[2048]. It takes 374 ms.

==> Buffer Size is 4096
DataInputStream[4096]. It takes 1263 ms.
BufferedInputStream[4096]. It takes 1208 ms.

==> Buffer Size is 8192
DataInputStream[8192]. It takes 1997 ms.
BufferedInputStream[8192]. It takes 1923 ms.

File Size is 577189779
==> Buffer Size is 1024
DataInputStream[1024]. It takes 17725 ms.
BufferedInputStream[1024]. It takes 6152 ms.

==> Buffer Size is 2048
DataInputStream[2048]. It takes 26353 ms.
BufferedInputStream[2048]. It takes 6864 ms.

==> Buffer Size is 4096
DataInputStream[4096]. It takes 16938 ms.
BufferedInputStream[4096]. It takes 8632 ms.

==> Buffer Size is 8192
DataInputStream[8192]. It takes 11091 ms.
BufferedInputStream[8192]. It takes 9306 ms.


 

 

이 글은 java 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.

LinkedList (Convert to Java)

package com.blogspot.coozplz;

 

/**

 * C로 배우는 알고리즘에 있는 

 * 연결 리스트를 자바로 구현.

 * @author Coozplz

 */

public class LinkedList1 {

    Node head;

    Node tail;

    

    public void initList() {

        head = new Node();

        tail = new Node();

        head.next = tail;

        tail.next = tail;

    }

    

    public void deleteNext(Node node) {

        Node temp;

        if(node.next.hashCode() == tail.hashCode()) {

            return ;

        }

        

        temp = node.next;

        node.next = node.next.next;

        temp = null;

    }

    

    

    public Node insertNode(int t, int k)  {

        Node s;

        

        Node p;

        

        Node r;

        

        p = head;

        s = p.next;

        while(s.key != k && s.hashCode() != tail.hashCode()) {

            p = p.next;

            s = p.next;

        }

        if(s.hashCode() != tail.hashCode()) {

            r = new Node();

            r.key = t;

            p.next = r;

            r.next = s;

        }

        return p.next;

    }

    

    public Node orderedInsert(int k) {

        Node s;

        Node p;

        Node r;

        p = head;

        s = p.next;

        while(s.key <= k && s.hashCode() != tail.hashCode()) {

            p = p.next;

            s = p.next;

        }

        r = new Node();

        r.key = k;

        p.next = r;

        r.next = s;

        return r;

    }

    

    

    public void printList(Node t) {

        System.out.println("Print Nodes");

        

        while(t.hashCode() != tail.hashCode()) {

            System.out.print("\t"+t.key);

            t = t.next;

        }

    }

    

    public static void main(String[] args) {

        LinkedList1 test = new LinkedList1();

        

        test.initList();

        test.orderedInsert(10);

        test.orderedInsert(5);

        test.orderedInsert(8);

        test.orderedInsert(3);

        test.orderedInsert(1);

        

        test.printList(test.head.next);

        

    }

    

}

 

class Node {

    int key;

    Node next;

}

자료구조 원형 큐

[출처] http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040201&docId=139457475

 

Question:

String 객체를 저장하는 큐를 원형 큐(배열)로 구현하고 이를
이용하는 프로그램을 작성하시오.
** 큐 연산 오류시 null을 리턴하도록 처리하든지, 예외 발생
하도록 처리하든지 각자 알아서 할 것
(1) StringCircularQueue 클래스
– private 인스턴스 변수
원형 큐 배열
기타 필요한 변수
– public 메소드
constructor 2가지
StringCircularQueue(int size) // size: 배열크기
StringCircularQueue()
enqueue
dequeue
isEmpty
toString
기타 필요한 메소드
(2) 드라이버 클래스의 main 메소드는 다음을 수행
– 크기가 5인 StringCircularQueue 큐를 생성
– 사용자에게 다음과 같은 메뉴를 제공하되, 4를 선택할 때까
지 계속 반복
1: 삽입, 2: 삭제, 3: 전체출력, 4: 종료
사용자가 1을 선택하면
사용자로부터 삽입할 한 줄의 문자열을 입력받음
큐에 그 문자열을 삽입(enqueue 메소드 호출)
큐가 꽉 찼는데 삽입을 시도했다면 어떤 방식으로든 실패
를 알려야 함
** enqueue 메소드에서 사용자 입력을 받도록 하면 안됨
사용자가 2를 선택하면
큐에 문자열을 삭제(dequeue 메소드 호출)
삭제한 문자열을 출력
큐가 텅 비었는데 삭제를 시도했다면 어떤 방식으로든 실
패를 알려야 함
** dequeue 메소드에서 문자열을 출력하도록 하면 안됨
사용자가 3을 선택하면
큐의 현재 내용을 모두 출력
front의 값이 가장 먼저,
rear의 값이 가장 마지막 나오도록
사용자가 4를 선택하면
반복을 마침
– 큐가 비어있는지 여부를 검사하여
만일 비어있지 않다면 큐가 텅 빌때까지 모든 원소를 삭제하
여 출력
———————————————————-
목적
– 배열로 구현한 원형 큐와 큐 연산을 익힌다.
———————————————————-
도와주세요 급합니다

Answer:

Difference about Scanner vs DataInputStream

[출처] http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040201&docId=139373099

Question:

숫자를 입력받을때

DataInputStream in = new DataInputStream(System.in);

int userNumber = Integer.parseInt(in.readLine());

이렇게 해서 입력받는거랑

Scanner sc = new Scanner(System.in)

int userNumber = sc.nextInt();

이거랑 무슨 차이가 있는거죠?

 

Answer:

이 글은 java 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.

정수 입력을 받아 각 자리수를 영어로 변환

[출처] http://kin.naver.com/qna/answer.nhn?dirId=1040201&docId=139424685

** Question: **
사용자로부터 정수를 입력받아서 각 자리수를 영어로 출력하는 프로그램을 작성하라. 소스좀

** Answer: **

package coozplz.blogspot.com;

import java.util.Scanner;

/**
 *

 * 사용자로부터 정수를 입력받아서 각 자리수를 
 * 영어로 출력하는 프로그램을 작성하라.
 * 
 * @author Coozplz
 */
public class ConvertNumberToString {

    // 0-9까지 해당하는 배열을 설정합니다.
    public static String[] numStr = new String[] {
              "Zero"
            , "One"
            , "Two"
            , "Three"
            , "Four"
            , "Five"
            , "Six"
            , "Seven"
            , "Eight"
            , "Nine"
            };
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("정수를 입력하시오: ");
        // 사용자가 입력한 정수값을 받습니다.
        // 입력값을 정수로 받아도 되지만 문자로 받아
        // charAt() 메소드를 이용하여 한글자씩 자르기 위함입니다.
        String input = scan.next(); 

        // 출력값을 저장하는 변수
        String result = "";

        // 입력받은 문자 길이만큼 반복합니다.
        for(int i=0, len=input.length(); i < len; i++) {
            // 문자중 한글자를 뽑습니다.
            char ch = input.charAt(i);

            // 출력값에 추가 합니다.

            result = result + numStr[Integer.parseInt(ch+"")]+" ";
        }
        System.out.println(result);
    }
}

자바 정규 표현식

Construct
Matches

Characters

x
The character x

\\
The backslash character

n
The character with octal value 0n (0 <= n <= 7)

nn
The character with octal value 0nn (0 <= n <= 7)

mnn
The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)

\xhh
The character with hexadecimal value 0xhh

\uhhhh
The character with hexadecimal value 0xhhhh

\t
The tab character (‘\u0009’)

\n
The newline (line feed) character (‘\u000A’)

\r
The carriage-return character (‘\u000D’)

\f
The form-feed character (‘\u000C’)

\a
The alert (bell) character (‘\u0007’)

\e
The escape character (‘\u001B’)

\cx
The control character corresponding to x

Character classes

[abc]
a, b, or c (simple class)

[^abc]
Any character except a, b, or c (negation)

[a-zA-Z]
a through z or A through Z, inclusive (range)

[a-d[m-p]]
a through d, or m through p: [a-dm-p] (union)

[a-z&&[def]]
d, e, or f (intersection)

[a-z&&[^bc]]
a through z, except for b and c: [ad-z] (subtraction)

[a-z&&[^m-p]]
a through z, and not m through p: [a-lq-z](subtraction)

Predefined character classes

.
Any character (may or may not match line terminators)

\d
A digit: [0-9]

\D
A non-digit: [^0-9]

\s
A whitespace character: [ \t\n\x0B\f\r]

\S
A non-whitespace character: [^\s]

\w
A word character: [a-zA-Z_0-9]

\W
A non-word character: [^\w]

POSIX character classes (US-ASCII only)

\p{Lower}
A lower-case alphabetic character: [a-z]

\p{Upper}
An upper-case alphabetic character:[A-Z]

\p{ASCII}
All ASCII:[\x00-\x7F]

\p{Alpha}
An alphabetic character:[\p{Lower}\p{Upper}]

\p{Digit}
A decimal digit: [0-9]

\p{Alnum}
An alphanumeric character:[\p{Alpha}\p{Digit}]

\p{Punct}
Punctuation: One of !”#$%&'()*+,-./:;?@[\]^_`{|}~

\p{Graph}
A visible character: [\p{Alnum}\p{Punct}]

\p{Print}
A printable character: [\p{Graph}\x20]

\p{Blank}
A space or a tab: [ \t]

\p{Cntrl}
A control character: [\x00-\x1F\x7F]

\p{XDigit}
A hexadecimal digit: [0-9a-fA-F]

\p{Space}
A whitespace character: [ \t\n\x0B\f\r]

java.lang.Character classes (simple java character type)

\p{javaLowerCase}
Equivalent to java.lang.Character.isLowerCase()

\p{javaUpperCase}
Equivalent to java.lang.Character.isUpperCase()

\p{javaWhitespace}
Equivalent to java.lang.Character.isWhitespace()

\p{javaMirrored}
Equivalent to java.lang.Character.isMirrored()

Classes for Unicode blocks and categories

\p{InGreek}
A character in the Greek block (simple block)

\p{Lu}
An uppercase letter (simple category)

\p{Sc}
A currency symbol

\P{InGreek}
Any character except one in the Greek block (negation)

[\p{L}&&[^\p{Lu}]]
Any letter except an uppercase letter (subtraction)

Boundary matchers

^
The beginning of a line

$
The end of a line

\b
A word boundary

\B
A non-word boundary

\A
The beginning of the input

\G
The end of the previous match

\Z
The end of the input but for the final terminator, if any

\z
The end of the input

Greedy quantifiers

X?
X, once or not at all

X*
X, zero or more times

X+
X, one or more times

X{n}
X, exactly n times

X{n,}
X, at least n times

X{n,m}
X, at least n but not more than m times

Reluctant quantifiers

X??
X, once or not at all

X*?
X, zero or more times

X+?
X, one or more times

X{n}?
X, exactly n times

X{n,}?
X, at least n times

X{n,m}?
X, at least n but not more than m times

Possessive quantifiers

X?+
X, once or not at all

X*+
X, zero or more times

X++
X, one or more times

X{n}+
X, exactly n times

X{n,}+
X, at least n times

X{n,m}+
X, at least n but not more than m times

Logical operators

XY
X followed by Y

X|Y
Either X or Y

(X)
X, as a capturing group

Back references

\n
Whatever the nth capturing group matched

Quotation

\
Nothing, but quotes the following character

\Q
Nothing, but quotes all characters until \E

\E
Nothing, but ends quoting started by \Q

Special constructs (non-capturing)

(?:X)
X, as a non-capturing group

(?idmsux-idmsux)
Nothing, but turns match flags on – off

(?idmsux-idmsux:X)
X, as a non-capturing group with the given flags on – off

(?=X)
X, via zero-width positive lookahead

(?!X)
X, via zero-width negative lookahead

(?<=X)
X, via zero-width positive lookbehind

(?<!X)
X, via zero-width negative lookbehind

(?>X)
X, as an independent, non-capturing group

이 글은 java 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.