【问题标题】:My removeDownTo() method does not show the correct output [duplicate]我的 removeDownTo() 方法没有显示正确的输出 [重复]
【发布时间】:2019-07-03 19:50:35
【问题描述】:

我正在做我的教授告诉全班做的这个练习。 “写一个方法 public static void removeDownTo (StackX stack, long ob):它将所有值弹出 堆栈到但不包括它看到的等于第二个参数的第一个元素。如果 没有一个是相等的,将堆栈留空。”

这是我的代码。

StackX类:

public class StackX {
    private static int maxSize; // size of stack array
    private static long[] stackArray;
    private int top; // top of stack
    //--------------------------------------------------------------
    public StackX(int s) // constructor
    {
        maxSize = s; // set array size
        stackArray = new long[maxSize]; // create array
        top = -1; // no items yet
    }
    //--------------------------------------------------------------
    public void push(long j) // put item on top of stack
    {
        stackArray[++top] = j; // increment top, insert item
        /**      if (isFull() ) {
                  System.out.println("Push error: Stack is full. Push failed.");
              } else {
                  stackArray[++top] = j;
              } */
    }
    //--------------------------------------------------------------
    public long pop() // take item from top of stack
    {
        return stackArray[top--]; // access item, decrement top
        /**      if(!isEmpty()) {
                  return stackArray[top--];
              } else {
                  System.out.println("Error: Stack is empty. Returning -1");
                  return -1;
              }
            */
    }

    //--------------------------------------------------------------
    public long peek() // peek at top of stack
    {
        return stackArray[top];
    }
    //--------------------------------------------------------------
    public boolean isEmpty() // true if stack is empty
    {
        return (top == -1);
    }
    //--------------------------------------------------------------
    public boolean isFull() // true if stack is full
    {
        return (top == maxSize - 1);
    }
}

StackApp类:

public class StackApp
   {

  public static void removeDownTo(StackX stack, long n) {
      long x;
      while(!stack.isEmpty()) {
          x = stack.peek();
          stack.pop();
          if(stack.isEmpty()) {
              if(x==n) {
                  stack.push(x);
              }
          }
      }
  }

   public static void main(String[] args)
      {
      StackX theStack = new StackX(10);  // make new stack
      theStack.push(20);               // push items onto stack
      theStack.push(40);
      theStack.push(60);
      theStack.push(80);
    //  theStack.push(16);
     // theStack.push(10);

      while( !theStack.isEmpty() )     // until it's empty,
         {                             // delete item from stack
         long value = theStack.pop();
         System.out.print(value);      // display it

         System.out.print(" ");

         }  // end while

      System.out.println("");
      removeDownTo(theStack, 60);
      System.out.print("");
      }  // end main()
   }  // end class StackApp ##

这是它显示的输出: 80、60、40、20。

但是,我认为这个练习要求的输出是 60、40、20。我做错了什么?

【问题讨论】:

  • 我认为你错过了你在这里实际做的事情。首先,始终如一地重新格式化您的代码,它必须看起来不错才能被理解。现在,看看“main”方法中的“while”循环,你只是在“弹出”和显示,很明显你会在控制台输出中看到 80、60、40、20。
  • 为什么你的if(x==n)if(stack.isEmpty()) 里面检查?为什么在考虑重新添加“downTo”目标之前必须清除堆栈?
  • 那我不把 removeDownTo(theStack, 60) 放在 while 循环里面吗?
  • @Alice 我需要纠正自己。在 removeDownTo 方法中移除元素后,可以循环(弹出每个元素)Stack 并显示剩余元素。
  • 嘿,非常感谢您的帮助!我将使用这些技巧来提高我的编程技能。是的,可以阅读

标签: java stack


【解决方案1】:

所以,我会尽量让这个答案更具教育意义。

首先,静态成员(或您喜欢的字段):

private static int maxSize;
private static long[] stackArray;

静态成员在StackX 的所有实例之间共享,因此,假设您实例化第二个StackX 对象,第一个将“看到”并使用新的maxSizestackArray 值。这不是你想要的。现在没关系,因为您使用的是单个 StackX 对象。

二、变量/参数命名。避免使用诸如xjn 之类的名字,他们只是对他们在项目中的角色只字未提。使用更具表现力的术语,例如sizevaluedownTo

第三,cmets。我看你喜欢写很多cmets,那很好。但请记住使用正确的工具。要表达方法或类的作用,请使用 JavaDoc。仅将线路 cmets 留作内部详细信息。

第四,尽量在成员(字段)、变量和参数上使用final。请记住,可变性(即您允许对象在执行期间更改的程度)通常很糟糕。

第五,使用异常来表示某些东西工作不正常。例如,堆栈已满,有人试图插入一个新值?抛出带有描述性消息的异常。

第六,始终格式化您的代码!无论是几行还是一百万行,都要格式化,避免行长过长。

public class StackX {
    private final int maxSize;
    private final long[] stackArray;
    private int top;

    public StackX(final int size) {
        maxSize = size;
        stackArray = new long[maxSize];
        top = -1;
    }

    /** Puts an item on top of the stack. */
    public void push(final long value) {
        if (isFull()) {
            throw new UnsupportedOperationException("Stack is full");
        }

        stackArray[++top] = value;
    }

    /** Takes an item from top of the stack. */
    public long pop() {
        if (isEmpty()) {
            throw new UnsupportedOperationException("Stack is empty");
        }

        return stackArray[top--];
    }

    /** Peeks an item at top of the stack. */
    public long peek() {
        return stackArray[top];
    }

    /** Returns {@code true} if stack is empty. */
    public boolean isEmpty() {
        return top == -1;
    }

    /** Returns {@code true} if stack is full. */
    public boolean isFull() {
        return top == maxSize - 1;
    }
}

public class Main {
    public static void main(final String[] args) {
        final StackX stackX = new StackX(5);
        stackX.push(20);
        stackX.push(40);
        stackX.push(60);
        stackX.push(80);

        removeDownTo(stackX, 60);

        // Prints remaining elements
        while (!stackX.isEmpty()) {
            System.out.println(stackX.pop());
        }

        System.out.println(stackX.isEmpty());
    }

    private static void removeDownTo(
            final StackX stack,
            final long downTo) {
        while (!stack.isEmpty()) {
            if (stack.peek() == downTo) {
                return;
            }

            stack.pop();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-27
    • 2020-10-26
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多