简体   繁体   中英

Null Pointer Exception When no value is null

I have the following code:

import java.io.File;

// Example of a BookStore main-class using CommandReader to read commands from input files.

public class BookStore {
    //Declarations
    String title;
    String seller;
    int price;

    public static void main(String[] args) throws BookStoreException {

        ListMultiIndex mi = new ListMultiIndex();   
        File file = new File ("Commands/commands_1_adds.txt");
        CommandReader reader = new CommandReader(file);
        String add = "add";
        String remove = "remove";
        while (reader.hasNext()){
            String [] command = reader.next();
            if((add).equals(command[0])){
               mi.add(command[1], command[2],Integer.parseInt(command[3])); 
               System.out.println("Book Added:");
               System.out.println("Title - " + command[1]);
               System.out.println("Seller - " + command[2]);
               System.out.println("Price - £" + command[3]);
               System.out.println("");

            }
            else if(command[0].equals(remove)){
                BookItem book = new BookItem(command[1], command[2], Integer.parseInt(command[3]));
                mi.remove(book);
                System.out.println("Book Removed:");
                System.out.println("Title - " + command[1]);
                System.out.println("Seller - " + command[2]); 
                System.out.println("Price - " + command[3]);
            }
            else System.out.println("Error:Retype the command, you've spelt 'add' or 'remove' wrong");
        }

    }

}

I keep getting Null Pointer Exception at: if((add).equals(command[0]))

Any help Appreciated, Thanks

您是否检查过命令是否为空?

if(command != null && add.equals(command[0])){ ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM