
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for(int i=0; i<N; i++) {
String str = sc.next();
if(str.equals("push"))
st.push(sc.nextInt());
else if (str.equals("top"))
if(st.empty()) {
System.out.println(-1);
}
else {
System.out.println(st.peek());
}
else if (str.equals("size")) {
System.out.println(st.size());
}
else if (str.equals("empty")) {
if(st.empty()) {
System.out.println(1);
}
else {
System.out.println(0);
}
}
else if (str.equals("pop")) {
if(st.empty()) {
System.out.println(-1);
}
else {
System.out.println(st.pop());
}
}
}
}
}
.equals()를 사용하지 않고 == 비교를 하여 컴파일 에러가 발생 -> == 비교는 문자열의 내용이 아닌 참조(주소)를 비교하기 때문에 .equlas()를 사용해야 문자열 내용 비교를 정확하게 가능
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
St st = new St(N);
for(int i=0; i<N; i++) {
String str = sc.next();
switch(str) {
case "push" :
st.push(sc.nextInt());
break;
case "pop" :
st.pop();
break;
case "size" :
st.size();
break;
case "empty" :
st.empty();
break;
case "top":
st.top();
break;
}
}
}
}
class St {
int[] arr;
int count = -1;
public St(int size) {
arr = new int[size];
}
void push(int a) {
count++;
arr[count] = a;
}
void pop() {
if(count < 0) {
System.out.println(-1);
}
else {
System.out.println(arr[count]);
count--;
}
}
void size() {
System.out.println(count + 1);
}
void empty() {
if (count < 0) {
System.out.println(1);
}
else {
System.out.println(0);
}
}
void top() {
if(count < 0) {
System.out.println(-1);
}
else {
System.out.println(arr[count]);
}
}
}
기본 생성자를 추가하지 않아 배열에서 런타임에러가 발생