2014-10-14 2 views
0

все. В настоящее время у меня проблема с оценкой выражения postfix в Java, и я думаю, что все в порядке, за исключением того, что вывод не совсем прав. Но неважно, пожалуйста, позвольте мне опубликовать все коды, чтобы все вы могли посмотреть на них. Кстати, пожалуйста, обратите внимание, что вам достаточно всего сосредоточиться на классе TestPalindrome, потому что я никогда не меняю коды для других классов, кроме класса, указанного мной сейчас.Странный выход (квадратный символ) в коде Java

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 и ASCII код 2, который 50 должен быть отображен вместо странных квадратных symbol.Thanks потому что тратить драгоценное время на изучение моей проблемы.

ответ

2

Вы говорите:

Пожалуйста, объясните неправильную часть, как я действительно не могу понять, почему это будет происходить, так как 1 + 1 = 2 и ASCII код 2, который 50 должен будет отображаться вместо странный квадратный символ.

Да, 1 + 1 = 2. Но если вы приводите его к полукокса, он будет использовать значение ASCII 2, а не 50. Для того, чтобы сделать это, вы должны сделать что-то вроде:

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

Другими словами: '0' != 0.

Однако это кажется неправильным подходом, потому что: что, если результат больше 9. Вам понадобятся два символа. Может, вам стоит подумать о другом дизайне?

+1

Я очень рад, что это утверждение resultCharIn = (char) ('0' + result); действительно дает то, что я хочу. С другой стороны, спасибо за ваше мягкое напоминание, потому что без напоминания я не смогу заметить, что в коде есть недостатки. Итак, я хотел бы сказать тысячу благодаря вам :) – user3310635

Смежные вопросы