Why do I get a NullPointerException?

I keep getting this NullPointer Exception when i run the code below with the following data file(input.dat):
5
1-2 1-3 2-4 3-4 4-5
I've spent over 2 hours on this and cant figure it out. Here is my codeimport java.io.*;
import java.util.*;
import java.lang.*;
class ClassOb {
    String classNumber;
    String classRelation;
public class Test {
        ClassOb[] co;
        public Test () throws Exception {
                Read("input.dat");
        public void Read(String fileName) {
                String num; //number of cells
                String cells = " "; //cell data
                int number;
                int x = 0;
                try {
                        FileReader file = new FileReader(fileName);
                        BufferedReader in = new BufferedReader (file);
                        num = in.readLine();
                        number = Integer.valueOf(num).intValue();
                        co = new ClassOb[number];
                        System.out.println("There are " + number + " total classes");
                        while ((cells = in.readLine()) != null) {
                                StringTokenizer st = new StringTokenizer(cells, "- ");
                                while (st.hasMoreTokens()) {
                                   co[x].classNumber = st.nextToken();
                                   co[x].classRelation = st.nextToken();
                                       x++;
                catch (IOException e) {
                        System.out.println("cannot read file");
                        System.exit(0);
                for (int k = 0; k < x; k++) {
                     System.out.println(co[k].classNumber + "-" + co[k].classRelation);
        public static void main (String[] args) throws Exception {
                new Test ();
} thanks for your help!

try this:
At the top, make your ClassOb declaration like this:
ClassOb[] co = new ClassOb[10];//Or some number more than high enough
Then, loop like this:
while ((cells = in.readLine()) != null) {
System.out.println("cells : " + cells);
StringTokenizer st1 = new StringTokenizer(cells, " ");
while(st1.hasMoreTokens()){
String ST1 = st1.nextToken();
System.out.println("ST1 : " + ST1);
StringTokenizer st2 = new StringTokenizer(ST1, "-");
String ST2 = st2.nextToken();
System.out.println("ST2 : " + ST2);
co[x] = new ClassOb();
co[x].classNumber = ST2;
ST2 = st2.nextToken();
System.out.println("ST2 : " + ST2);
co[x].classRelation = ST2;
x++;
Not sure if this is the desired output, but I got this at the end:
1-2
1-3
2-4
3-4
4-5
Polarbear

Similar Messages

  • Why am i getting this NullpointerException?

    i have an applet in which there are panels.
    i have a subclass panel which extends a superclass panel.
    in the superclass, there is an instance of a different panel.
    when i try to call the getX() method of the different panel in the subclass, it gives me a nullpointerexception.
    code:
    import java.net.URL;
    class Slime extends Enemy
         Slime(URL cb,Chara ch)
              super(cb,ch,"slimeup1.png","slimeup2.png","slimedown1.png","slimedown2.png","slimeleft1.png","slimeleft2.png","slimeright1.png","slimeright2.png");
              setSize(30,35);
              setOpaque(false);
              damage=10;
              display(DownPicture1);
         public void run(){
              int cntr=0;
              while(!stopThread)
                   if(cntr>=200)
                   cntr=0;
                   else
                   if(cntr<=100){
                   setLocation(getX()+1,getY());
                   animate(RightPicture1,RightPicture2);
                   dir=3;
                   cntr++;
                   else
                   if(cntr>=100){
                   setLocation(getX()-1,getY());
                   animate(LeftPicture1,LeftPicture2);
                   dir=4;
                   cntr++;}
                   System.out.println(Integer.toString(c.getX()));
    System.out.println(Integer.toString(getCharaX() ));
              //problem is using the getCharaX() and getCharaY() from the Enemy class (the super class)
                   try{Thread.sleep(20);}catch(Exception e){}
    }

    It's not clear from your description where you're really having that exception. But if you'd look at the stack trace that prints, it would tell you. And the reason would simply be that you have an object reference which equals null at the time that the code is trying to invoke a method on it. Such as,
    String x = null;
    int len = x.length(); <-- NullPointerException, because x == null

  • Why am I getting "Can't write file"? from jsp

    I have the following code:
    public String OpenRAF(String fileName) {
    try {
    file = new File("http://www.domain/filename.prn");
    } catch (java.lang.NullPointerException npe) {
    writeError(npe);
    } catch (java.lang.IllegalArgumentException iae) {
    writeError(iae);
    if (!file.isFile()) {
    retn = "Not a file:" + file.getAbsoluteFile();
    if (!file.canRead()) {
    retn = "Can't read file:" + file.getAbsoluteFile();
    if (!file.canWrite()) {
    retn = "Can't write file:" + file.getAbsoluteFile();
    try {
    raf = new java.io.RandomAccessFile(file, "rw");
    } catch (java.io.FileNotFoundException fnfe) {
    rtn = false;
    Why am I getting the "Can't write file http://www.domain/filename" from this jsp?
    I would like to open this file read,write and update it with the RandomAccessFile api, but I can't seem to get write permissions. I have granted 777 permissions on the file.
    Is this a Tomcat file permission issue or something?
    Thanks.

    Thanks,
    But I want to read,write to a file in the application Server. How do I get the path correct?
    I want to use something like java.io.RandomAccessFile("somepath", "rw");
    I should be able to access the filesystem somehow? The only way I could find the file was using the URL. Whenever I used a relative or absolute path, I could not access the file.
    How do I know what the filesystem path is on an application server (Tomcat 4.1) from a Jsp 1.4?
    Thanks again

  • Why am I getting this exception???

    Every once in a while I get the following exception when starting my app, and I can't figure out why... Why??
    java.lang.NullPointerException
         at javax.swing.SwingUtilities.computeIntersection(SwingUtilities.java:369)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:404)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    This is actually a very hard question. Swing is designed to be fast so it is not thread safe. That means if you do something to a swing component while its being painted, you get this type of exception. Notice how it does not mention your own code anywhere in the stack trace. The "Event Dispatcher Thread' is trying to paint something and you are probably changing its size, setting its visibility to false, removing it form its container, moving it, changing the data in its model, etc. Your code is doing something to the component at the exact moment its being painted, and this exception is thrown.
    There are two general strategies for dealing with this problem:
    1) When you modify swing components, use SwingUtilities.invokeLater() to make the event dispatcher thread do the work.
    2) Do your work in a synchronized block, something that looks like this (say you are removing rows from a table):
    synchronized ( table.getTreeLock() ) {
      // do work here...
    }Either of these strategies will prevent this type of error from happening. It's a tought problem, since it can happen anywhere, is usually hard to reproduce, and difficult to verify it's actually fixed.

  • Why do i get f4 on field in alv report  ?

    i done general (MM) alv report
    And i display "MATKL" (Material Group) in one of the column.
    I don't know why, but when i stand on the data  , i get f4 option
    , when i asking for f4 i get message, u201CNo input help is availableu201D.
    In the definition, I didnu2019t put the matkl original data element  ,
    I just put char9, i didnu2019t ask/build and double click or
    Event for it.
    so why do i get f4 option in this column  ?
    thanks  .

    Ajay said the correct answer...
    chech this sample code:
    CLEAR  wa_catalog.
      wa_catalog-fieldname = 'BANFN'.
      wa_catalog-ref_table = 'EBAN'.
      APPEND wa_catalog TO catalog.
    Edited by: Sebastian Bustamante on Oct 6, 2008 9:40 PM

  • Why do we get the data from a view to a report.

    hi
    why do we get the data from a view to a report. is it possible to get the data from a view in all the cases?

    hi Jyotssna,
      Suppose you are planning to get the data from multiple tables then you got to specify seveal condtions and make use of joins which results in poor performance in fetching the data . In order to improve the performance we make use of views where the conditions of different tables are defined and the data is fetched accordingly.
    Regards,
    Santosh

  • Why would I get ReferenceError #1065: "Variable title is not defined."

    Well of course it's not defined.  It's a dynamic class, and strict mode compilation is turned off so that I don't have to declare the property to compile it.
    I've created a library item named "Page" with a single TextField instance named "title".
    Page's class is defined in an ActionScript file, and it's assigned to the library item in export for ActionScript.
    Page's ActionScript file defines the class as a "dynamic" class, so I should not be getting this runtime error.  I turned off strict mode compiling, since it seems to be designed to check the presense of property definitions at compile time for dynamic classes like MovieClip.
    public dynamic class Page extends MovieClip
        public function Page()
            super();
            var text:String = title.text; //title can be moused over in the debugger here and shows the correct value, but the flash player throws a runtime error when it tries to access it, but it shouldn't because this is a dynamic class.
    So why am I getting a runtime error for the field "title".  It makes no sense, because if I step to that line in the FlashDevelop debugger and hold the mouse over "title", it shows that it is in fact the instance of the TextField that I'm trying to access.  Yet the player throws an error when I actually try to access it.
    Is it a problem or limitation with the access style (i.e. would it work fine if I accessed it as "this.title" or "this["title"]"?

    Nevermind.  This was apparently a browser caching issue.   The Page base class is defined in the main interface swf, and is externally referenced through its swc in an external "lesson" file that declare a subclass of Page.  It was this custom subclass of Page which was throwing the error (basically the same as the simplified example I wrote for my post, where it simply tried to access "title" as a dynamic property of the Page).  What happened is the browser was caching an old version of the lesson file with the old definition of the class that was not declared as dynamic.  I had received the error before, then updated the class, then I was surprised to see the error persist.  It suddenly dawned on me that the browser was probably caching the old version, so I cleared the cache and it seems to work fine now.
    Actually, it is a problem after all.  I forgot I had updated it to use "this.title" syntax on the page I tested after clearing the cache, but the other pages that try to access title directly as "title" still throw the error.  So it seems to be some sort of quirk in how flash accesses properties of a dynamic class.  If you try to access them direclty, it must do so in a way that requires the property to be defined, but if you access it via "this.title" or this["title"], the it seems to resolve the property value without throwing the error.
    This sucks.  I was really trying to not have to write "this." for every property.  The entire display list is dynamically generated from some custom XML that allows me to call constructors and set complex type-safe properties, and during construction it was copying each item into a Dictionary by name.  This Dictionary was then assigned to the page class as "items", so I was accessing each display object as "item.name".  Then I got the brilliant idea of just making Page and its subclasses "dynamic" so that I could just add the DIctionary values on the Page instance itself.  I thought I would be able to access the dyamic properties just by their name such as "title", but lo and behold, Flash strikes again, and I have to use dot notation anyway.  What do you all think?  Any solutions?

  • Why did I get an email from the fraud dept saying my order is on hold, told to call a number, and then told by dept it's not true?

    I placed an order to upgrade my phone yesterday, and the order went through, I was told the new phone would arrive Thursday. After I got home from work today I saw an email from Verizon that says "Dear Customer:
    Verizon Fraud Prevention Team is currently reviewing the following order on your wireless account. Please call the Verizon Fraud Prevention Team at 888-483-7200 option 3, press 1 to verify this Order."
    I called this number immediately, since I need this phone ASAP, assuming it would just be a recording and I would have to verify an account number or something. But instead, after following the instructions, I was put on hold because I needed to speak to someone in person. After several instances of my call being cut off after being on hold for at least half an hour, I finally got through after three hours and was able to speak to a fraud representative. I gave her my info and told her the problem and she told me I had called the wrong department. Instead of the fraud department, I needed the online order department. She transferred me, and I waited on hold again. When the representative from the online order dept picked up, she first told me if it was a fraud issue I'd need to speak with the fraud dept - who had JUST transferred me to her. After this, she said that my order is not on hold, because it hasn't even been processed yet or had the credit check done. When I asked if this meant I hadn't needed to call at all, she said yes. Is this actually true or is there a chance that there's an issue with my order I don't know about? If there is no issue, these emails really shouldn't be sent out, they're incredibly misleading, and I've wasted a whole lot of time and experienced an incredible amount of anxiety for no reason.

    Hi.  I checked on the order and it says the order is currently being processed and I should check back tomorrow. I'm mostly just concerned because I got an email saying the order was on hold, and I want to make sure it actually does go through and I'm not just waiting for a delivery that's not going to come. I'm still confused as to why I'd get an email saying I had to call the fraud department only to be told I shouldn't have called the fraud department.

  • My iMac locks up constantly in email. I click on one or two emails. Then when I click on another email, I get the spinning wheel and have to relaunch. Why does it get confused and lock up?

    My iMac locks up constantly in email. I click on one or two emails. Then when I click on another email, I get the spinning wheel and have to relaunch. Why does it get confused and lock up? Seems like it is stuck.

    10.6.8 here, MacBook Pro. Comcast. Mail  freeze ups. Occasional warnings to use "Log Out" under the Apple icon.
    Disk Repair run several times. Shows lots of Java  "remote" issues.
    I run Disk Repair several times, shows a lot of Java, "remote" issues.
    Restart don't know if it helps, I do it all the time. What's with quitting Mail but it doesn't quit, and why a separate maneuver to "Log Out".
    i

  • TS1702 "The feature you are trying to use is on a network resource that is unabailable" Why am I getting this message when I try to updaate itunes or quicktime?

    The feature you are trying to use is on a network resource that is unabailable" Why am I getting this message when I try to updaate itunes or quicktime?

    Before trying the update again, use Microsoft's Fix it solution at http://support.microsoft.com/mats/Program_Install_and_Uninstall. Use it to uninstall iTunes and Quicktime. It bypasses this not uncommon problem. When the solution finishes, the selected program will be uninstalled. It can take several minutes and I have seen as much as half an hour.
    After iTunes & Quicktime are uninstalled, try the update again.

  • I am getting a NullPointerException when trying to use the Service class

    I am getting a NullPointerException which is as follows
    java.lang.NullPointerException
    file:/K:/Learner/JavaFx2/ProductApplication/dist/run166129449/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
      at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
    And my View SingleController is as follows
    package com.product.app.controller;
    import com.product.app.model.Product;
    import com.product.app.service.ViewProductsService;
    import com.product.app.util.JSONParser;
    import com.product.app.util.TagConstants;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.ResourceBundle;
    import javafx.collections.ObservableList;
    import javafx.concurrent.Service;
    import javafx.concurrent.Task;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ProgressIndicator;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Region;
    import javafx.stage.Stage;
    import javax.swing.JOptionPane;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;
    * FXML Controller class
    * @author Arun Joseph
    public class ViewSingleController implements Initializable {
        private static String action = "";
        @FXML
        private TextField txtID;
        @FXML
        private TextField txtName;
        @FXML
        private TextField txtPrice;
        @FXML
        private TextArea txtDesc;
        @FXML
        private Region veil;
        @FXML
        private ProgressIndicator p;
        private ViewProductsService service = new ViewProductsService();
        private JSONObject product = null;
        private JSONParser parser = new JSONParser();
        private int pid = 1;
        public void setPid(int pid) {
            this.pid = pid;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
            p.setMaxSize(150, 150);
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
            Product product = new Product();
            service.start();
            ObservableList<Product> products = service.valueProperty().get();
            products.get(pid);
            txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
            //product = service.valueProperty().get().get(pid);
            //txtID.setText(String.valueOf(product.getPid()));
            txtName.textProperty().set(product.getName());
            txtPrice.textProperty().set(String.valueOf(product.getPrize()));
            txtDesc.textProperty().set(product.getDescription());
        private SomeService someService = new SomeService();
        @FXML
        private void handleUpdateButtonClick(ActionEvent event) {
            action = "update";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleDeleteButtonClick(ActionEvent event) {
            action = "delete";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleCancelButtonClick(ActionEvent event) {
            closeStage();
        private void closeStage() {
            ViewSingleController.stage.close();
        private static Stage stage = null;
        public static void setStage(Stage stage) {
            ViewSingleController.stage = stage;
        private class SomeService extends Service<String> {
            @Override
            protected Task<String> createTask() {
                return new SomeTask();
            private class SomeTask extends Task<String> {
                @Override
                protected String call() throws Exception {
                    String result = "";
                    int success = 0;
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    switch (action) {
                        case "update":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            params.add(new BasicNameValuePair("name", txtName.getText()));
                            params.add(new BasicNameValuePair("price", txtPrice.getText()));
                            params.add(new BasicNameValuePair("description", txtDesc.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Updated the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                        case "delete":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Deleted the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                    return result;

    Time Machine has its own mechanism for deleting files. The number you are seeing may represent a "underflow" or a number of files which exceeds the limit and becomes negative.
    The best way to remove TM files is via the TM interface: select the files and click the Gear and select delete from all backups.
    If you are deleting files on an external drive which once included TM files, it is best to use the terminal and just delete them directly. They go bye-bye without ever seeing the trash bucket.
    Of course, using the terminal is not for everyone.
    What you might be able to do is restore the files from trash and then delete them properly or in smaller bundles.

  • Why do I get the "iwork discontinued" message when I click on the share feature in pages?

    Why do I get the "iwork discontinued" message when I click on the share feature in pages?

    If you are using an older version of iWorks, the sharing was, I understand discontinued in July 2012.
    New versions of the iWorks suite, Pages etc now have the sharing option, introduced earlier this year.

  • Why do I get a black screen when i click on a PDF in a web page?

    why do I get a black screen when i click on a PDF in a web page? Firefox works as is should.

    Hi,
    From your Safari menu bar click Safari / Preferences then select the Extensions tab. If you have any installed, turn that off, then relaunch Safari. Try a PDF file.
    If it's not Extensions, open a Finder window. Select MacintoshHD in the Sidebar on the left. Now open the Library folder then the Internet Plug-Ins folder. If you see any files such as this:
    AdobePDF Browser or Viewer Plug-in
    Move it to the Trash, relaunch Safari.
    Carolyn :-)

  • Why do I get a warning triangle error alert on my project in the time frame area. And how do I remove it

    Why do I get a yellow triangle looks like warning or alert symbol in my timeframe area. And what do I need to do to delete it?

    What is the "Timeframe" area?
    A clip in an Event, or a whole Event has lost track of it's originals.
    Did you delete anything in an Event that you were using in a Timeilne?

  • Why do I get shadows in the corners of pictures taken on my mini iPad?

    Why do I get shadows in the corners of pictures taken on my mini iPad.  It seems the conditions have to be perfect to get a decent picture.  Why?

    Sounds like vignetting, but you need to ask that on an iPad forum not the iPhoto for Mac one.

Maybe you are looking for

  • ITunes Store files don't work with Realplayer or Windows Media Player

    I tried posting a question but it did not allow me so I am going to try posting it here. I need some help but not sure where to go to post the questions or what e-mail address I can use to e-mail the appropiate place to get help so if you can help me

  • [ADF-11.1.2] Non Sense Associations and View Links while using Mysql as DB

    Hello, I recently started using Oracle ADF with MySQL at design time. I am following instruction from http://www.oracle.com/technetwork/developer-tools/jdev/mysql-and-bc-howto-082060.html With Jdeveloper, I created following tables with Mysql Databas

  • DBMS_CRYPTO.HASH produces a different hash result when I use it in sqlldr?

    Hello, If I execute the following in sqlplus: SELECT LOWER(SYS.DBMS_CRYPTO.HASH(UTL_RAW.CAST_TO_RAW(CONCAT('Salt','000000000')),3)) FROM DUAL; It produces one hash value. However, if I use similar logic in a sqlldr control file: OPTIONS (SKIP=7) LOAD

  • Mapping first node

    <Empid> <ID>   <No>12</No> </ID> <Name>        <FirstName>demo</FirstName>        <LastName>test</LastName> </Name> <Empid> I have to check if the first occurence of  FirstName in the Name node  as Test1 then map to target element. Somebody pelase he

  • Q10 not showing my facebook updates

    Someone please help! I was prompted to load a more recent version of FB, which i did. However now it doesn't show my status updates on my wall that i posted over the last couple of weeks. Nor any of my friends when i go into their walls. But I am get