반응형

문제

BorderLayout을 사용하여 컴포넌트 사이의 수평 수직 간격이 각가 5픽셀, 7픽셀이 되도록 스윙 응용프로그램을 작성하라.

 

소스 코드

import java.awt.*;
import javax.swing.*;
public class Main2 extends JFrame{
	public Main2(){
		setTitle("BorderLayout");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		Container c = getContentPane();
		
		c.setLayout(new BorderLayout(5,7));
		c.add(new JButton("North"),BorderLayout.NORTH);
		c.add(new JButton("West"),BorderLayout.WEST);
		c.add(new JButton("Center"),BorderLayout.CENTER);
		c.add(new JButton("East"),BorderLayout.EAST);
		c.add(new JButton("South"),BorderLayout.SOUTH);
		setSize(300,200);
		setVisible(true);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Main2();
	}

}

 

반응형
반응형

문제

다음 그림과 같이 "Let's study Java"라는 문자열을 타이틀로 가지고 프레임의 크기가 400x200인 스윙 프로그램을 작성하라.

 

소스 코드

import javax.swing.*;

public class Main1  extends JFrame{
	public Main1() {
		setTitle("Let's study Java");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,200);
		setVisible(true);

		}
	
	public static void main(String[] args) {
		new Main1();
	}

}

 

 

반응형
반응형

문제

Open Challenge를 수정하여 사용자가 단어를 삽입할 수 있도록 기능을 추가하라.

 

출력 예시

**** 영어 단어 테스트 프로그램 "명품영어" 입니다. ****
단어 테스트:1, 단어 삽입:2, 종료:3 >> 1
현재 17개의 단어가 들어 있습니다. -1을 입력하면 테스틑 종료합니다.
eye?
(1)눈 (2)동물 (3)사랑 (4)감정 :>1
Excellent !!
human?
(1)인간 (2)감정 (3)거래 (4)그림 :> 2
No. !!
fault?
(1)오류 (2)감정 (3)사회 (4)조각상 :> 1
Excellent !!
emotion?
(1)그림 (2)사랑 (3)거래 (4)감정 :> ㅁ러미  -잘못입력한경우
숫자를 입력하세요 !!
painting?
(1)거래 (2)눈 (3)애인 (4)그림 :> 4
Excellent !!
animal?
(1)사회 (2)그림 (3)동물 (4)눈 :> -1  -단어 테스트 종료

단어 테스트:1, 단어 삽입:2, 종료:3 >> 2
영어 단어에 그만을 입력하면 입력을 종료합니다.
영어 한글 입력 >> flag 깃발
영어 한글 입력 >>  friend 친구
영어 한글 입력 >>  computer 컴퓨터
영어 한글 입력 >>  imagine 상상
영어 한글 입력 >>  smile 웃음
영어 한글 입력 >>  그만

단어 테스트:1, 단어 삽입:2, 종료:3 >> 1
smile?
(1)상상 (2)사회 (3)웃음 (4)주식 :> 3
Excellent !!
freind?
(1)오류 (2)친구 (3)자기 (4)사진 :> 2
Excellent !!
dall?
(1)컴퓨터 (2)인형 (3)상상 (4) 사랑 :> -1

단어 테스트:1, 단어 삽입:2, 종료:3 >> 3
"명품영어"를 종료합니다.

 

소스 코드

import java.util.*;

class WordTest {
	HashMap<String,String> HM = new HashMap<String,String>();
	ArrayList<Boolean> Check = new ArrayList<Boolean>(); //문제를 냈는지 체크
	WordTest(){
		HM.put("love","사랑");
		HM.put("animal","동물");
		HM.put("emtion","감정");
		HM.put("human","인간");
		HM.put("stock","주식");
		HM.put("trade","거래");
		HM.put("society","사회");
		HM.put("baby","아기");
		HM.put("honey","애인");
		HM.put("dall","인형");
		HM.put("bear","곰");
		HM.put("picture","사진");
		HM.put("painting","그림");
		HM.put("fault","오류");
		HM.put("example","보기");
		HM.put("eye","눈");
		HM.put("statue","조각상");

		Scanner s = new Scanner(System.in);
		int Input;
		
		while(true) {
			System.out.println("**** 영어 단어 테스트 프로그램 \"명품영어\" 입니다. ****");
			System.out.print("단어 테스트: 1, 단어 삽입: 2, 종료: 3>>");
			Input  = s.nextInt();
			s.nextLine();
			switch(Input) {
			case 1:
				for(int i = 0;i<HM.size();i++)
					Check.add(false); //초기화
				System.out.println("현재 "+HM.size()+"개의 단어가 들어 있습니다. -1을 입력하면 테스트를 종료합니다");
				TestRun(s);
				System.out.println();
				break;
			case 2:
				System.out.println("영어 단어에 그만을 입력하면 입력을 종료합니다.");
				AddWord(s);
				System.out.println();
				break;
			case 3:
				System.out.println("\"명품영어\"를 종료합니다.");
				return;
			}
		}
	}
	private void TestRun(Scanner s) {
		Set<String> keys = HM.keySet();
		int TestTime = 0;
		while(true) {
			if(TestTime>=HM.size()) {
				System.out.println("모든 테스트를 진행하였습니다. 종료합니다.");
				return;
			}
			Iterator<String> it = keys.iterator();
			Iterator<String> it2 = keys.iterator();
			int size = HM.size()-1;
			int Random = (int)(Math.random()*size);
			String problem = "";
			if(Check.get(Random) != false)
				continue;
			int k = 0;
			while(it.hasNext()) {
				String temp=it.next();
				if(k == Random)
				{
					problem = temp;
				}
				k++;
			}
			TestTime++;
			System.out.println(TestTime + "번째 실행");
			System.out.println(problem);
			int order[] = new int[4];
			int random1,random2,random3;
			while(true) {
			random1 = (int)(Math.random()*size);
			random2 = (int)(Math.random()*size);
			random3 = (int)(Math.random()*size);
			if(random1 != random2 && random1 != random3 &&
					random1 != Random && random2 != random3 && 
					random2 != Random && random3 != Random)
				break;
			}
			
			order[0] = random1;
			order[1] = random2;
			order[2] = random3;
			order[3] = Random;
			
			Arrays.sort(order);
			int count = 0;
			for(int i =0;i<HM.size();i++)
			{
				String temp = it2.next();
				for(int j = 0;j<4;j++) {
					if(i == order[j])
						System.out.print("("+ ++count + ")" + HM.get(temp) + " ");
				}
			}
			System.out.print(" :> ");
			try {
			int Input = 0;
			Input = s.nextInt();
			if(Input == -1)
				break;
			else if(order[Input-1] == Random)
				System.out.println("Excellent !!");
			else
				System.out.println("NO. !!");
			}
			catch(InputMismatchException e) {
				System.out.println("숫자를 입력하세요 !!");
				s.nextLine();
				continue;
			}
		}
		
		
	}
	private void AddWord(Scanner s) {
		while(true) {
			System.out.print("영어 한글 입력 >> ");
			String eng = s.next();
			if(eng.equals("그만"))
				break;
			String kor = s.next();
			HM.put(eng, kor);
			Check.add(false);
		}
	}
}
public class Main12 {

	public static void main(String[] args) {
		new WordTest();
	}

}

테스트 횟수를 카운트하고 금 범위를 넘어가면 강제로 테스트 종료하여 메인 메뉴로 나가게 하였습니다.

반응형
반응형

문제

C:\temp에 있는 .txt 파일만 삭제하는 프로그램을 작성하라. C:\나 C:\wingdows 등의 디렉터리에 적용하면 중요한 파일이 삭제될 수 있으니 조심하라.

 

출력 예시

C:\temp디렉터리의 .txt 파일의 모두 삭제합니다....
C:\temp\p.txt 삭제
C:\temp\phone.txt 삭제
C:\temp\test.txt 삭제
총 3개의 .txt 파일을 삭제하였습니다.

 

소스 코드

import java.io.*;

public class Main9 {
	public static void DeleteFile(File temp) {
		File[] subFiles = temp.listFiles();
		int count=0;
		System.out.println("C:\\temp디렉터리의 .txt 파일의 모두 삭제합니다....");
		for(int i = 0;i<subFiles.length;i++)
		{
			String name = subFiles[i].getName();
			int index = name.lastIndexOf(".txt");
			if(index != -1)
			{
				subFiles[i].delete();
				count++;
				System.out.println("총 "+count+"개의 .txt파일을 삭제하였습니다.");
			}
		}
	}
	public static void main(String[] args) {
		File f = new File("파일경로");
		DeleteFile(f);
	}

}
반응형
반응형

문제

File 클래스를 이용하여 C:\에 있는 파일 중에서 제일 큰 파일의 이름과 크기를 출력하라.

 

출력 예시

가장 큰 파일은 C:\hiberfil.sys 3394002944바이트

 

소스 코드

import java.io.File;

public class Main8 {
	public static void MaxByteFile(File dir) {
		File[] subFiles = dir.listFiles();
		int Max = 0;
		File MAX = null;
		for(int i = 0;i<subFiles.length;i++)
		{
			File temp = subFiles[i];
			if(Max < temp.length()) {
				Max = (int)temp.length();
				MAX = temp;
			}			
		}
		System.out.println("가장 큰 파일은"+MAX.getPath()+" "+ Max + "바이트");
	}
	public static void main(String[] args) {
		File f = new File("C:\\");
		MaxByteFile(f);
	}

}
반응형
반응형

문제

파일 복사 연습을 해보자. 이미지 복사가 진행하는 동안 10% 진행할 때마다 '*' 하나씩 출력하도록 하라. 아래 예시는 프로젝트 폴더 밑에 a.jpg을 미리 준비해두었다.

 

출력 예시

a.jpg를 b.jpg로 복사합니다.
10%마다 *를 출력합니다.
**********

 

소스 코드

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main7 {

	public static void main(String[] args) {
		File src = new File("파일경로\\a.jfif");
		File dest = new File("파일경로\\b.jfif");
		int c;
		int count = 0,div = 1;
		try {
			FileInputStream fi = new FileInputStream(src);
			FileOutputStream fo = new FileOutputStream(dest);
			System.out.println(src.getPath() + "를 "+ dest.getPath()+"로 복사합니다");
			System.out.println("10%마다 *를 출력합니다");
			while((c=fi.read())!=-1) {
				fo.write((byte)c);
				count++;
				if(((src.length())/10*div ) == count ) {
					System.out.print("*");
					div++;
				}
			}
			fi.close();
			fo.close();
			
		}catch(IOException e) {
			System.out.println("파일 복사 오류");
		}
	}

}

jpg가 아닌 jfif그림파일을 사용했습니다.

 

a.jfif
0.02MB
b.jfif
0.02MB

반응형
반응형

문제

사용자로부터 두 개의 텍스트 파일 이름을 입력받고 첫 번째 파일 뒤에 두 번째 파일을 덧붙인 새로운 파일을 생성하는 프로그램을 작성하라. 아래 실행 예시에서는 프로젝트 폴더에 elvis1.txt와 elvis2.txt를 미리 준비해 두었다.

 

출력 예시

전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다.
첫번째 파일 이름을 입력하세요>>elvis1.txt
두번째 파일 이름을 입력하세요>>elvis2.txt
프로젝트 폴더 밑에 appended.txt. 파일에 저장하였습니다.

 

소스 코드

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

public class Main6 {
	public static void main(String[] args) {
		FileReader fin1 = null;
		FileReader fin2 = null;
		FileWriter fin3 = null;
		BufferedReader bufReader1 = null,bufReader2 = null;
		String Line1 = "",Line2 = "";
		String File1,File2;
		Scanner s = new Scanner(System.in);
		
		System.out.println("전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다.");
		try {
			System.out.print("첫번째 파일 이름을 입력하세요>>");
			File1 = s.nextLine();
			System.out.print("두번째 파일 이름을 입력하세요>>");
			File2 = s.nextLine();
			fin1 = new FileReader("파일경로"+File1);
			fin2 = new FileReader("파일경로"+File2);
			fin3 = new FileWriter("파일경로\\appended.txt");
			bufReader1 = new BufferedReader(fin1);
			bufReader2 = new BufferedReader(fin2);
			while((Line1 = bufReader1.readLine())!=null) {
				fin3.write(Line1,0,Line1.length());
				fin3.write("\r\n", 0, 2);	
			}
			while((Line2 = bufReader2.readLine())!=null) {
				fin3.write(Line2,0,Line2.length());
				fin3.write("\r\n", 0, 2);	
			}
			
			System.out.println("프로젝트 폴더 밑에 appended.txt 파일에 저장하였습니다.");
			fin1.close();
			fin2.close();
			fin3.close();
			bufReader1.close();
			bufReader2.close();
		}
		catch(IOException e) {
			System.out.println("입출력 오류");
		}
		s.close();
	}
}

elvis1.txt
0.00MB
elvis2.txt
0.00MB
appended.txt
0.00MB

반응형
반응형

문제

2개의 파일을 입력받고 비교하여 같으면 "파일이 같습니다." , 틀리면 "파일이 서로 다릅니다."를 출력하는 프로그램을 작성하라. 텍스트 및 바이너리 파일 모두를 포함한다. 아래 실행 예시에서는 프로젝트 폴더에 elvis1.txt와 복사본 elvis1-복사본.txt를 미리 준비해 두었다.

 

출력 예시

전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다.
첫번째 파일 이름을 입력하세요>>elvis1.txt
두번째 파일 이름을 입력하세요>>elvis1-복사본.txt
elvis1.txt와 elvis1-복사본.txt를 비교합니다.
파일이 같습니다.

 

소스 코드

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

public class Main5 {

	public static void main(String[] args) {
		FileReader fin1 = null;
		FileReader fin2 = null;
		int c1,c2;
		String File1,File2;
		boolean check = true;
		Scanner s = new Scanner(System.in);
		
		System.out.println("전체 경로명이 아닌 파일 이름만 입력하는 경우, 파일은 프로젝트 폴더에 있어야 합니다.");
		try {
			System.out.print("첫번째 파일 이름을 입력하세요>>");
			File1 = s.nextLine();
			System.out.print("두번째 파일 이름을 입력하세요>>");
			File2 = s.nextLine();
			fin1 = new FileReader("파일경로"+File1);
			fin2 = new FileReader("파일경로"+File2);
			System.out.println(File1+" 와 "+File2+"를 비교합니다.");
			while((c1 = fin1.read())!=-1&&(c2 = fin2.read()) != -1) {
				if(c1 != c2)
					check = false;
			}
            fin1.close();
            fin2.close();
			if(check)
				System.out.println("파일이 같습니다.");
			else
				System.out.println("파일이 서로 다릅니다.");
		}
		catch(IOException e) {
			System.out.println("입출력 오류");
		}
	}
}

파일 위치에 따라 파일경로 설정하시면 됩니다.

elvis1 - 복사본.txt
0.00MB
elvis1.txt
0.00MB

 

반응형
반응형

문제

C:\windows\system.ini 파일에 라인 번호를 붙여 출력하라.

출력 예시

 1: ; for 16-bit app support
 2: [386Enh]
 3: woafont=dosapp.fon
 4: EGA80WOA.FON=EGA80WOA.FON
 5: EGA40WOA.FON=EGA40WOA.FON
 6: CGA80WOA.FON=CGA80WOA.FON
 7: CGA40WOA.FON=CGA40WOA.FON
 8: 
 9: [drivers]
10: wave=mmdrv.dll
11: timer=timer.drv
12: 
13: [mci]

 

소스 코드

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main4 {
	public static void main(String[] args)
	{
		FileReader fin = null;
		BufferedReader bufReader = null;
		try {
			fin = new FileReader("C:\\windows\\system.ini");
			bufReader = new BufferedReader(fin);
			String line = "";
			int count = 1;
			while((line = bufReader.readLine()) != null) {
				System.out.printf("%3d: ",count);
				System.out.println(line);
				count++;
			}
			fin.close();
			bufReader.close();
		}
		catch(IOException e) {
			System.out.println("입출력 오류");
		}
	}
}
반응형
반응형

문제

C:\windows\system.ini 파일을 읽어 소문자를 모두 대문자로 바꾸어 출력하라.

 

소스 코드

import java.io.*;

public class Main3 {
	public static void main(String[] args)
	{
		FileReader fin = null;
		
		try {
			fin = new FileReader("C:\\windows\\system.ini");
			int c;
			while((c=fin.read())!=-1) {
				c = Character.toUpperCase(c);
				System.out.print((char)c);
			}
			fin.close();
		}
		catch(IOException e) {
			System.out.println("입출력 오류");
		}
	}
}
반응형

+ Recent posts