[문제3] 사용자가 입력한 명령라인의 내용을 저장하는 save(String input)메서드와 사용자가 입력한 명령라인의 이력을 보여주는 history()메서드를 완성하세요.
[예제ConsoleEx3.java]
import java.util.*;
class ConsoleEx3 {
static String[] argArr; // 입력한 매개변수를 담기위한 문자열배열
static LinkedList q = new LinkedList(); // 사용자가 입력한 내용을 저장할 큐(Queue)
static final int MAX_SIZE = 5; // q(큐)에 저장될 수 있는 값의 개수
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // 한번만 생성해서 재사용하면 되므로 반복문 밖으로 이동
while(true) {
String prompt = ">>";
System.out.print(prompt);
// 화면으로부터 라인단위로 입력받는다.
String input = s.nextLine();
save(input);
input = input.trim(); // 입력받은 값에서 불필요한 앞뒤 공백을 제거한다.
argArr = input.split(" +");
String command = argArr[0].trim();
if("".equals(command)) continue;
command = command.toLowerCase(); // 명령어를 소문자로 바꾼다.
if(command.equals("q")) { // q 또는 Q를 입력하면 실행종료한다.
System.exit(0);
} else if(command.equals("history")) { // equalsIgnoreCase대신 equals를 사용.
history();
} else {
for(int i=0; i < argArr.length;i++) {
System.out.println(argArr[i]);
}
}
} // while(true)
} // main
public static void save(String input) {
if(input==null || "".equals(input)) return;
/*
다음의 코드를 완성하세요.
1. queue에 저장한다.
2. queue의 최대크기(MAX_SIZE)를 넣으면 제일 오래된 저장값을 삭제한다.
*/
}
// 사용자가 입력한 최근 명령을 보여주는 메서드
public static void history() {
int i=0;
/*
다음의 코드를 완성하세요.
1. LinkedList에 저장된 내용(최근 MAX_SIZE개의 명령어)을 보여준다.
*/
}
} // class
[실행결과]
>>hello
hello
>>hello2
hello2
>>hello3
hello3
>>hello4
hello4
>>history
1.hello
2.hello2
3.hello3
4.hello4
5.history
>>history
1.hello2
2.hello3
3.hello4
4.history
5.history
>>q
https://cafe.naver.com/javachobostudy/24689
LinkedLisk를 처음 써봤다. 문제를 풀면서 모르는 것을 자연스럽게 접하니까 좋다.ㅎㅎ LinkedList는 여기를 참고하였다. 코딩테스트 문제 풀 때 활용하면 좋을거같다.
import java.util.LinkedList;
import java.util.Scanner;
class ConsoleEx3 {
static String[] argArr;
static LinkedList<String> q = new LinkedList<String>();
static final int MAX_SIZE = 5;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(true) {
String prompt = ">> ";
System.out.print(prompt);
String input = s.nextLine();
save(input);
input = input.trim();
argArr = input.split("\\s+");
String command = argArr[0].trim();
if("".equals(command)) continue;
command = command.toLowerCase();
if(command.equals("q")) {
System.exit(0);
} else if(command.equals("history")) {
history();
} else {
for(int i=0; i < argArr.length;i++) {
System.out.println(argArr[i]);
}
}
}
}
public static void save(String input) {
if(input==null || "".equals(input)) return;
q.addLast(input);
if (q.size() > MAX_SIZE) {
q.removeFirst();
}
}
public static void history() {
for (int i = 0; i < q.size(); i++) {
System.out.println((i + 1) + "." + q.get(i));
}
}
}
답을 알기 위해 4번 문제를 가져왔다. 굳이 addLast()나 removeFirst()라 명시하지 않아도 add()는 가장 마지막에 추가하며, remove()는 가장 앞의 값을 삭제한다. 또 LinkedList에 있는 값을 출력하기 위해 get() 메소드를 사용한 것이 아닌 Iterator객체를 만들어 출력하였다. LinkedList는 배열처럼 인덱스로 연결된 것이 아닌 각 노드의 포인터로 연결되어 있기 때문에 값 검색 시 순차탐색을 해야해서 많은 시간이 소요된다. 현재 예제는 크기가 5로 제한되어 있었기 때문에 성능에 문제는 없었으나 어차피 순차적으로 출력해야 한다면 4번 문제처럼 Iterator를 사용하는 것이 좋다.
import java.util.*;
import java.io.*;
class ConsoleEx4 {
static String[] argArr; // 입력한 매개변수를 담기위한 문자열배열
static LinkedList q = new LinkedList(); // 사용자가 입력한 내용을 저장할 큐(Queue)
static final int MAX_SIZE = 5; // Queue에 최대 5개까지만 저장되도록 한다.
static File curDir; // 현재 디렉토리
static {
/*
다음의 코드를 완성하세요.
1. 시스템속성 "user.dir"값을 읽어서 File객체를 만들고, curDir에 할당하세요.
2. 1의 코드를 간단히 예외처리하세요.
*/
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // 한번만 생성해서 재사용하면 되므로 반복문 밖으로 이동
while(true) {
try {
String prompt = curDir.getCanonicalPath() + ">>";
System.out.print(prompt);
// 화면으로부터 라인단위로 입력받는다.
String input = s.nextLine();
save(input);
input = input.trim(); // 입력받은 값에서 불필요한 앞뒤 공백을 제거한다.
argArr = input.split(" +");
String command = argArr[0].trim();
if("".equals(command)) continue;
command = command.toLowerCase(); // 명령어를 소문자로 바꾼다.
if(command.equals("q")) { // q 또는 Q를 입력하면 실행종료한다.
System.exit(0);
} else if(command.equals("history")) {
history();
} else {
for(int i=0; i < argArr.length;i++) {
System.out.println(argArr[i]);
}
}
} catch(Exception e) {
System.out.println("입력오류입니다.");
}
} // while(true)
} // main
public static void save(String input) {
if(input==null || "".equals(input)) return;
q.add(input); // queue에 저장한다.
// queue의 최대크기를 넣으면 제일 오래된 저장값을 삭제한다.
if(((LinkedList)q).size() > MAX_SIZE)
q.remove();
}
public static void history() {
int i=0;
// LinkedList의 내용을 보여준다.
ListIterator it =q.listIterator();
while(it.hasNext()) {
System.out.println(++i+"."+it.next());
}
}
} // class