java - Java代码中的奇怪输出(方形符号)

标签 java stack

大家。我目前在 Java 中对后缀表达式进行求值时遇到问题,我认为除了输出不太正确之外一切都很好。不过没关系,我把所有的代码贴出来,方便大家看一下。顺便说一句,请注意,大家只需要专注于 TestPalindrome 类就足够了,因为除了我刚才指定的类之外,我从未更改过其他类的代码。

StackInterface 定义了 ArrayStack 类可用的所有方法。

      //There is no need to check this.
      public interface StackInterface<T> {
      /** Task: Adds a new entry to the top of the stack.
       *  @param newEntry  an object to be added to the stack */
      public void push(T newEntry);

      /** Task: Removes and returns the stack誷 top entry.
       *  @return either the object at the top of the stack or, if the
       *          stack is empty before the operation, null */
      public T pop();

      /** Task: Retrieves the stack誷 top entry.
       *  @return either the object at the top of the stack or null if
       *          the stack is empty */
      public T peek();

      /** Task: Detects whether the stack is empty.
       *  @return true if the stack is empty */
      public boolean isEmpty();

      /** Task: Removes all entries from the stack */
      public void clear();
    } // end StackInterface

ArrayStack 类没什么特别的。

//There is no need to check this.
public class ArrayStack<T> implements StackInterface<T> {
    private T[] stack;    // array of stack entries
    private int topIndex; // index of top entry
    private static final int DEFAULT_INITIAL_CAPACITY = 50;

    public ArrayStack() {
    this(DEFAULT_INITIAL_CAPACITY);
    } // end default constructor

    public ArrayStack(int initialCapacity) {
        stack = (T[]) new Object[initialCapacity];
        topIndex = -1;
    } // end constructor

    public void push(T newEntry) {
        topIndex++;

    if (topIndex >= stack.length) // if array is full,
        doubleArray();              // expand array

        stack[topIndex] = newEntry;
    } // end push

    public T peek() {
        T top = null;

        if (!isEmpty())
            top = stack[topIndex];

        return top;
    } // end peek

    public T pop() {
        T top = null;

        if (!isEmpty()) {
            top = stack[topIndex];
            stack[topIndex] = null;
            topIndex--;
        } // end if

        return top;
    } // end pop

    public boolean isEmpty() {
        return topIndex < 0;
    } // end isEmpty

    public void clear() {

    } // end clear

    /** Task: Doubles the size of the array of stack entries.
     *        Refer to Segment 5.18 */
    private void doubleArray() {
    T[] oldStack = stack;                // get reference to array of stack entries
      int oldSize = oldStack.length;       // get max size of original array

      stack = (T[]) new Object[2 * oldSize]; // double size of array

      // copy entries from old array to new, bigger array
    System.arraycopy(oldStack, 0, stack, 0, oldSize);
    } // end doubleArray
} // end ArrayStack

下面的类是TestPalindrome类。(类名可能听起来很奇怪,因为我做的练习都在同一个类中,并且我不会在类中发布不相关的代码。)

import java.util.Scanner;

public class TestPalindrome {

    public TestPalindrome() {
    }

    public static void main(String[] args) {

        //P3Q2

        StackInterface<Character> myStack = new ArrayStack<Character>();
        Scanner scanner = new Scanner(System.in);
        int result;
        char resultInChar;

        System.out.print("Please enter a postfix expresion : ");
        String postfix = scanner.nextLine();

        for(int i = 0; i < postfix.length(); i++)
        {
            char postfixChar = postfix.charAt(i);

            if(Character.isDigit(postfixChar)) //If postfixChar is a digit, then it will be pushed into the stack.
            {
                myStack.push(postfixChar);
            }


                 /*(For else statement) First operand will be popped as right operand and second 
operand will be popped as left operand if postfixChar is operator such as + .
The calculation of both operands will be carried out based on the operator given. 
After this the result of calculation will be pushed back into the stack and the 
same things will happen again.*/ 

            else 
            {
                int firstOperand = Character.getNumericValue(myStack.pop()); //To get numeric value of the first character stored. 
                System.out.println("\nThe right operand : " + firstOperand);
                int secondOperand = Character.getNumericValue(myStack.pop()); //To get numeric value of the second character stored.
                System.out.println("The left operand : " + secondOperand);

                switch(postfixChar)
                {
                    case '+':
                        result = secondOperand + firstOperand;
                        System.out.println("The result is " + result);
                        resultInChar = (char)result; //Convert the result of calculation back to character data type so that it can be pushed into the stack.
                        System.out.println("Strange output : " + resultInChar); //Here is where the strange output occurred. 
                        myStack.push(resultInChar);
                        break;

                    case '-':
                        result = secondOperand - firstOperand;
                        System.out.println("The result is " + result);
                        resultInChar = (char)result;
                        myStack.push(resultInChar);
                        break;

                    case '/':
                        result = secondOperand / firstOperand;
                        System.out.println("The result is " + result);
                        resultInChar = (char)result;
                        myStack.push(resultInChar);
                        break;

                    case '*':
                        result = secondOperand * firstOperand;
                        System.out.println("The result is " + result);
                        resultInChar = (char)result;
                        myStack.push(resultInChar);
                        break;
                }
            }
        }

        System.out.println("\nThe answer of " + postfix + " is " + Character.getNumericValue(myStack.pop())); //To get the final answer in the form of numeric value
    }
}

这是图片的附件,显示了程序的所有输出。

enter image description here

请解释错误的部分,因为我真的不明白为什么会发生这种情况,因为 1 + 1 = 2 并且应该显示 2 的 ASCII 代码(50)而不是奇怪的方形符号。谢谢,因为花费了宝贵的时间看看我的问题。

最佳答案

你说:

Please explain the wrong part as I really cannot figure out why this will happen since 1 + 1 = 2 and the ASCII code of 2 which is 50 should be displayed instead of the weird square symbol.

是的,1 + 1 = 2。但是如果将其转换为字符,它将使用 ASCII 值 2,而不是 50。为此,您应该执行以下操作:

resultCharIn = (char) ('0' + result);

换句话说:'0' != 0

但是,这似乎是一个错误的方法,因为:如果结果大于 9 怎么办。您将需要两个字符。也许您应该考虑不同的设计?

关于java - Java代码中的奇怪输出(方形符号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366446/

相关文章:

c++ - C++强制堆栈内部函数展开

Java SWT 列表错误, "null pointer exception"

java - 在 Java 中使用 Switch 语句时遇到问题

java - 如何使用mysql在jtable中显示Url Image?

java - 正交投影 - 使物体适合屏幕?

java - 在 ArrayList 中找不到超过 99 的值

python - 在python中获取pdb风格的调用者信息

c - 如何更正这些 "Expected Expression Before ' Stack '"and "Not Enough Arguments to Function 'Push' 错误?

检测到 C 堆栈崩溃

java - 如何读取堆栈的所有元素而不弹出它们?