我尝试创建一个与用户交互的堆栈。它将提供逐个或全部数据弹出数据的选择。我的问题是,当我尝试弹出一个数据时,它会给我空字符串。
这是我的代码:
package Tugas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myStack {
private static Stack<Integer> stack;
private static int size;
public static void main(String[] args) {
System.out.println("Enter amount numbers : ");
size = inputData();
createStack(size);
readData();
Scanner scanner = new Scanner(System.in);
System.out.println("Take it All (y) or one by one (n)");
String input = scanner.next();
if (input.equals("y")) {
writeData();
} else {
popData();
writeData();
String confirm;
Scanner scanner2 = new Scanner(System.in);
System.out.println("Take again ? ");
confirm = scanner2.next();
if (confirm.equals("y")) {
popData();
writeData();
}
}
}
private static void createStack(int size) {
stack = new Stack<>();
}
private static void writeData() {
int dataStack;
System.out.println(" The contains of data: ");
for (int i = 0; i < size; i++) {
try {
dataStack = stack.pop();
System.out.println("Value of stack at " + (i + 1) + " : " + dataStack);
} catch (EmptyStackException e) {
}
}
}
private static void readData() {
int data;
System.out.println("===== all data =====");
for (int i = 0; i < size; i++) {
System.out.print("The data at : " + (i + 1) + " : ");
data = inputData();
stack.push(data);
}
}
private static void popData() {
int dataStack;
System.out.println("=== Pop a data : ===");
dataStack = stack.pop();
}
private static Integer inputData() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = br.readLine();
} catch (IOException ex) {
Logger.getLogger(Tumpukan.class.getName()).log(Level.SEVERE, null, ex);
}
int data = Integer.parseInt(input);
return data;
}
}
感谢您的帮助...
答案 0 :(得分:2)
您弹出数据两次:
进入:
popData();
然后在循环中:
writeData();
这意味着writeData
将是一个短元素,因为它已被popData
弹出。