如何修复我的Java堆栈< t>代码我获得了NullPoInterException?

发布于 2025-01-24 22:39:00 字数 1576 浏览 3 评论 0原文

创建一个代表堆栈的堆栈通用类(将项目放在堆栈顶部,从堆栈顶部删除项目,查询最上方的项目,查询大小,在错误的情况下抛出异常!<)! /p>

我该如何解决?我没有任何想法。

import java.util.*;

public class Stack<T> {
    private T[] stack = null;
    private int size = 0;

    public void push(T x) {
       stack[size] = x;
       size++;
      }
    public T pop() throws Exception{
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return stack[size];
        }
     }
    public T top() throws Exception {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return stack[size-1];
        }
      }
    public int size() {
       return size;
      }

public static void main(String[] args) throws Exception{
    
    Stack<Integer> stack1 = new Stack<Integer>();

        stack1.push(213);
        stack1.push(345);
        stack1.push(987);

        while(stack1.size() > 0){
            System.out.println(stack1.pop());
        }

        System.out.println("\n");

        Stack<String> stack2 = new Stack<String>();

        stack2.push("1");
        stack2.push("2");
        stack2.push("3");
        stack2.push("4");

        while(stack2.size() > 0){
            System.out.println(stack2.pop());
        }
    
}
}

I got an error message :
Exception in thread "main" java.lang.NullPointerException
        at Stack.push(Stack.java:12)
        at Stack.main(Stack.java:41)

Create a Stack generic class that represents a stack (placing an item on top of the stack, removing an item from the top of the stack, querying the topmost item, querying the size, throwing exceptions in case of errors)!

How can I fix this? I do not have any idea.

import java.util.*;

public class Stack<T> {
    private T[] stack = null;
    private int size = 0;

    public void push(T x) {
       stack[size] = x;
       size++;
      }
    public T pop() throws Exception{
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return stack[size];
        }
     }
    public T top() throws Exception {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return stack[size-1];
        }
      }
    public int size() {
       return size;
      }

public static void main(String[] args) throws Exception{
    
    Stack<Integer> stack1 = new Stack<Integer>();

        stack1.push(213);
        stack1.push(345);
        stack1.push(987);

        while(stack1.size() > 0){
            System.out.println(stack1.pop());
        }

        System.out.println("\n");

        Stack<String> stack2 = new Stack<String>();

        stack2.push("1");
        stack2.push("2");
        stack2.push("3");
        stack2.push("4");

        while(stack2.size() > 0){
            System.out.println(stack2.pop());
        }
    
}
}

I got an error message :
Exception in thread "main" java.lang.NullPointerException
        at Stack.push(Stack.java:12)
        at Stack.main(Stack.java:41)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的笑 2025-01-31 22:39:00

使用行private t [] stack = null;您不初始化数组。因此,在调用pop() top(),push(t)上时,您将获得NullPoInterException。

您想念的是堆栈的构造函数,在该堆栈中,您必须通过堆栈的最大容量,然后必须初始化具有该大小的数组。

import java.util.NoSuchElementException;

@SuppressWarnings("unchecked")
public class Stack<T> {
    private final int capacity; // remember capacity
    private final Object[] stack; // array of type Object
    private int size = 0;

    public Stack(int capacity) {
        this.capacity = capacity;
        this.stack = new Object[capacity]; // initialize new array
    }

    public void push(T x) {
        if (size == capacity) { // check for sufficient capacity
            throw new IllegalStateException("Stack is full.");
        }
        stack[size] = x;
        size++;
    }
    public T pop() {
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return (T) stack[size]; // cast result
        }
    }
    public T top() {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return (T) stack[size-1]; // cast result
        }
    }
    public int size() {
        return size;
    }
}

请注意,容量是您堆栈可以维护的最大数据大小,而大小将是当前使用的容量。在将某些东西推入之前,您还将检查足够的容量。作为
@rzwitserloot 提到的是创建一个通用数组而不是琐碎的,最简单的是创建一个对象阵列并将其铸造为检索阵列他们的条目。

否则(这更复杂)在添加某些内容时,您必须动态调整后端数组的大小,或者将数组的数组切换为ArrayList。

With the line private T[] stack = null; You don't initialize an array. Therefore you get NullPointerException when calling pop(), top(), push(t)on it.

What you miss is a constructor for your stack, where you pass the max capacity for the stack and after that you have to initialize an array with that size.

import java.util.NoSuchElementException;

@SuppressWarnings("unchecked")
public class Stack<T> {
    private final int capacity; // remember capacity
    private final Object[] stack; // array of type Object
    private int size = 0;

    public Stack(int capacity) {
        this.capacity = capacity;
        this.stack = new Object[capacity]; // initialize new array
    }

    public void push(T x) {
        if (size == capacity) { // check for sufficient capacity
            throw new IllegalStateException("Stack is full.");
        }
        stack[size] = x;
        size++;
    }
    public T pop() {
        if (size == 0) {
            throw new NoSuchElementException("Cannot pop from empty stack");
        }else{
            size--;
            return (T) stack[size]; // cast result
        }
    }
    public T top() {
        if (size == 0) {
            throw new NoSuchElementException("The stack is empty");
        }else{
            return (T) stack[size-1]; // cast result
        }
    }
    public int size() {
        return size;
    }
}

Note, that capacity is the max size of data your stack can maintain and size would be the currentl capacity in use. You would also check for sufficient capacity before pushing something onto it. As
@rzwitserloot mentioned is the creation of an generic array not trivial, the easiest would be to create an Object array and casting the retrieval of their entries.

Otherwise (which is much more complicated) you have to dynamically resize the backend array when adding something to it, while it is full or switch the array for an ArrayList.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文