gpt4 book ai didi

java - 弹出栈顶失败

转载 作者:行者123 更新时间:2023-12-02 05:11:03 26 4
gpt4 key购买 nike

我尝试创建一个与用户交互的堆栈。它将提供一个选择是逐个弹出数据还是全部数据。我的问题是,当我尝试仅弹出数据时,它给我空字符串。

这是我的代码:

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;
}
}

感谢您的帮助...

最佳答案

您弹出数据两次:

一旦进入:

    popData();

然后在循环中:

    writeData();

这意味着 writeData 将少一个元素,因为它已经被 popData 弹出。

关于java - 弹出栈顶失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27341882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com