퀴즈
- makeNewArray 메서드와 copy 메서드를 새로 생성
-> 함수는 잘게 쪼개야 좋기 때문에
package day03;
import java.util.Arrays;
public class MethodQuiz {
static String[] foods = {"떡볶이", "치킨", "파스타"};
static String[] userNames = {"홍길동", "고길동"};
static void printFoods() {
System.out.println(Arrays.toString(foods));
}
static String[] makeNewArray(int size) {
return new String[foods.length + size];
}
static String[] copy(int size) {
String[] temp = makeNewArray(size);
int loopCount = (size >= 0) ? foods.length : temp.length;
for (int i = 0; i < loopCount; i++) {
temp[i] = foods[i];
}
return temp;
}
static void push(String newFood) {
String[] temp = copy(1);
temp[temp.length - 1] = newFood;
foods = temp;
}
static int indexOf(String food) {
for (int i = 0; i < foods.length; i++) {
if (food.equals(foods[i])) {
return i;
}
}
return -1;
}
static void pop() {
foods = copy(-1);
}
static void remove(String deleteTarget) {
int index = indexOf(deleteTarget);
if (index == -1) return;
for (int i = index; i < foods.length - 1; i++) {
foods[i] = foods[i+1];
}
pop();
}
static boolean include(String searchTarget) {
return indexOf(searchTarget) != -1;
}
static void insert(int targetIndex, String newFood) {
if (isOufOfBounds(targetIndex)) return;
String[] temp = copy(1);
for (int i = temp.length - 1; i > targetIndex; i--) {
temp[i] = temp[i - 1];
}
temp[targetIndex] = newFood;
foods = temp;
}
static void modify(int targetIndex, String newFood) {
if (isOufOfBounds(targetIndex)) return;
foods[targetIndex] = newFood;
}
static boolean isOufOfBounds(int targetIndex) {
return targetIndex < 0 || targetIndex > foods.length - 1;
}
public static void main(String[] args) {
printFoods();
push("라면");
push("김치찌개");
printFoods();
int index = indexOf("파스타");
System.out.println("index = " + index);
int index2 = indexOf("라면땅");
System.out.println("index2 = " + index2);
remove("치킨");
printFoods();
boolean flag1 = include("파스타");
System.out.println("flag1 = " + flag1);
boolean flag2 = include("떡라면");
System.out.println("flag2 = " + flag2);
insert(3, "파인애플");
printFoods();
modify(2, "닭갈비");
printFoods();
}
}