user2975455
user2975455

Reputation: 15

failed to pop the top of stack

I try to create a stack that will be interactive to the user. It will give a choice to pop a data one by one or all of the data. My problem is, when I try to pop just a data, it gives me empty string.

Here's my code :

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

Thanks for the help ...

Upvotes: 0

Views: 60

Answers (1)

Eran
Eran

Reputation: 393821

You pop data twice :

Once in :

    popData();

And then in a loop in :

    writeData();

This means writeData will be one element short, since it was already popped by popData.

Upvotes: 2

Related Questions