Java: Null Pointer Deque Iterator

前端 未结 2 1372
天涯浪人
天涯浪人 2021-01-15 17:45

I\'ve been assigned to write a class that takes a mathematical expression in infix notation and turns that expression into an equivalent one in postfix notation. That part I

相关标签:
2条回答
  • 2021-01-15 18:05

    You problem is about scoping of your data field postfix

    This is what you have :

    public class InfixToPostfix{
    
        private Deque<String> postfix; <-- this is data field 
    
        public InfixToPostfix(String infix){
    
            Deque<String> postfix = new LinkedList<String>();
                             ^
                             |   
    you declared that reference here again which shadows the data field. 
    postfix is just visible in constructor and out of here your data field
    is still pointing to null value.
    

    change it to

    postfix = new LinkedList<String>(); 
    

    as a result you will instantiate the postfix and when you want to access it , it will never be null because you instantiated the data field postfix.

    Some Suggestions:

    1. you can use diamond inference since Java 7

    For example:

     List<String> myList = new ArrayList<String>();
    

    can be written

      List<String> myList = new ArrayList< >();
                                          ^
                                          |
    

    and if you can choose different name for your iterator function in below code is better because you may confuse whoever reads your code

    public Iterator<String> iterator(){
            return new PostfixIterator(postfix);
        }
    
    0 讨论(0)
  • 2021-01-15 18:07

    It seems that you declare variable "postfix" twice, you should use the class variable "postfix" only.

    public class InfixToPostfix{
    
       private Deque<String> postfix;
    
       public InfixToPostfix(String infix){
    
            postfix = new LinkedList<String>();
            // Code here
       }
    }
    
    0 讨论(0)
提交回复
热议问题