Help with Exception in thread "main" java.lang.NullPointerException

I got this exception while running the code in Netbeans IDE 6.1. The code is compiling fine...Please tell me what the problem is
Exception in thread "main" java.lang.NullPointerException
at Softwareguide.chooseanswer(Softwareguide.java:32)
at Driver.main(Driver.java:7)
public class Driver
    public static void main(String[] args)
        Softwareguide swguide = new Softwareguide();
        swguide.chooseanswer();
public class Softwareguide
    State test1;
    State test2;
    State test3;
    State test4;
    State test5;
    State subtest1;
    State subtest2;
    State subtest3;
    State subtest4;
    State subtest5;
    State state = test1;
    public Softwareguide()
        test1 = new Test1(this);
        test2 = new Test2(this);
        test3 = new Test3(this);
        test4 = new Test4(this);
        test5 = new Test5(this);
        subtest1 = new SubTest1(this);
        subtest2 = new SubTest2(this);
        subtest3 = new SubTest3(this);
        subtest4 = new SubTest4(this);
        subtest5 = new SubTest5(this);
    public void chooseanswer()
        state.chooseanswer();
   /* public void chooseyes()
        state.chooseyes();
    public void chooseno()
        state.chooseno();
    public State getState()
        return state;
    void setState(State state)
     this.state = state;
    public State getTest1State()
        return test1;
    public State getTest2State()
        return test2;
    public State getTest3State()
        return test3;
    public State getTest4State()
        return test4;
    public State getTest5State()
        return test5;
    public State getsubTest1State()
        return subtest1;
    public State getsubTest2State()
        return subtest2;
    public State getsubTest3State()
        return subtest3;
    public State getsubTest4State()
        return subtest4;
    public State getsubTest5State()
        return subtest5;
    public String toString()
        StringBuffer result = new StringBuffer();
        result.append("\n Starting Diagnostic Test...");
        return result.toString();
}

spiderjava wrote:
the variable state is assigned to test1. This variable(test1) is not initialized anywhere.It is initialized in the c'tor. Which is invoked after the "global" object and attribute initialization. So it is there, but comes too late.
You should definitly not write a technical Java blog and post it all over the place.

Similar Messages

  • Need help with Exception in thread "main" java.lang.NullPointerException

    here is the error
    Exception in thread "main" java.lang.NullPointerException
    at stream.createFrame(stream.java:153)
    at chat.createMessage(chat.java:14)
    this is where the error is in stream
    public void createFrame(int id) {
              *buffer[currentOffset++] = (byte)(id + packetEncryption.getNextKey());*
    and this is where it comes from in chat
    outStream.createFrame(85);                    
    i just cant see whats causeing the exception

    spiderjava wrote:
    the variable state is assigned to test1. This variable(test1) is not initialized anywhere.It is initialized in the c'tor. Which is invoked after the "global" object and attribute initialization. So it is there, but comes too late.
    You should definitly not write a technical Java blog and post it all over the place.

  • Re: Exception in thread "main" java.lang.NullPointerException

    Hi
    I am getting the following error. I cannot see any uninitialised objects. I have spent enough time on it .Could someone help me with this.
    Thanks in advance
    Exception in thread "main" java.lang.NullPointerException
            at pointlist.pointList.add(pointList.java:31)
            at pointlist.pointList.main(pointList.java:67)
            at pointlist.pointList.add(pointList.java:31)
            at pointlist.pointList.main(pointList.java:67)
    package pointlist;
    import javax.vecmath.Point2d;
    public class pointList extends Point2d{
        protected transient int size = 0;
        protected Point2d[] pointList = new Point2d[10];
        public pointList(){       
        public void add(int x,int y){
            if(pointList.length == size)
                resize(pointList.length * 2);
                System.out.print(size+"\n");
            pointList[size].setX(x);
            pointList[size].setY(y);       
            System.out.print(x+"\n"+y);       
            size++;
            System.out.print("\n"+size);
        public int size(){
            if(size <= 0)
            return(0);
            else
            return(size-1);
        private void resize(int newsize){
            Point2d[] newpointList = new Point2d[newsize]; // Create a new array
        public int[] get(int index){
            if(index>size)
                      throw new ArrayIndexOutOfBoundsException(index);
            else
                int[] point = new int[2];
                point[0] = (int)pointList[index-1].x;
                point[1] = (int)pointList[index-1].y;
                return(point);
    public static void main(String args[]){
        pointList plist = new pointList();
        plist.add(10, 10);
    }

    An Object-array (or in your case an array of Point2D) is just an array of references in Java.
    With "new Point2D[10]" you've created an array capable of holding 10 references to Point2D objects, but you've not yet created an Point2D object (each of those references is null). You'll need to create such a Point2D object in your add() method (before you try to call setX() and setY() on it).
    Two additional hints:
    * Your class should really be called PointList, because class names should start with a upper-case letter in Java
    * your resize method doesn't keep the old values, but simply creates a new (empty) array.

  • Exception in thread "main" java.lang.NullPointerException

    hi
    I am new to Java, and taking an introductory course in java. I wrote the code given bellow and get following error "C:\java\assingment2>java test123
    Exception in thread "main" java.lang.NullPointerException
    at PartCatalog.Add(test123.java:56)
    at test123.main(test123.java:102)"
    Can any body help me please
    import java.util.*;
    class PartRecord
    public String PartName;
    public String PartNumber;
    public float Cost;
    public int Quantity;
    public static int counter ;
    public PartRecord()
    { PartName ="";
         PartNumber="";
    Cost = 0;
         Quantity = 0;
         counter = 0;
    public void Set(String name, final String num,
    float cost, int quantity)
         PartName = name;
    PartNumber= num;
    Cost = cost;
    Quantity = quantity;
    counter++;
    public float Get()
                   return Cost*Quantity;
    public static int Counter() {return counter;}
    class PartCatalog
    public PartCatalog()
    npart=0;
    public void Add(String name, String num,
    float cost, int quantity)
    if(npart>=1000) return;
    Parts[npart++].Set(name,num,cost,quantity);
    public float ShowInventory()
    int inventory = 0;
    for(int i=0; i<npart; i++)
    inventory+= Parts.Get();
    return inventory;
    public PartRecord[] Parts = new PartRecord[1000];
    public int npart;
    class ExtPartCatalog extends PartCatalog
    public void Sort()
    Arrays.sort(Parts);
    public void Print()
    for(int i=0; i<npart; i++)
    System.out.println ( Parts[i].PartName + "\t "
    + Parts[i].PartNumber + "\t "
    + Parts[i].Cost + "\t "
    + Parts[i].Quantity + "\n");
    class test123{
    public static void main(String args[])          
         ExtPartCatalog catalog = new ExtPartCatalog();
         catalog.Add("tire ", "1", 45, 200);
         catalog.Add("microwave", "2", 95, 10);
         catalog.Add("CD Player", "3", 215, 11);
         catalog.Add("Chair ", "4", 65, 10);
         catalog.Sort();
    catalog.Print();
    System.out.println("Inventory is " + catalog.ShowInventory());
    ExtPartCatalog catalog2 = new ExtPartCatalog();
    catalog2.Add("ttt ", "1", 45, 200);
    System.out.print("\n\nTotally there are " + PartRecord.Counter() );
    System.out.println(" Parts being set" );

    Thank you for your reply. I think i used
    public PartRecord[] Parts = new PartRecord[1000];
    so i have created the reference. I tries what you told me but it still did not work. I am putting the code again, but now in the formatted form so that you can read it more easily. I will appreciate your help. Thanks
    <code>
    import java.util.*;
    class PartRecord
    {      public String PartName;
    public String PartNumber;
    public float Cost;
    public int Quantity;
    public static int counter ;
         public PartRecord()
              PartName ="";
              PartNumber="";
              Cost = 0;
              Quantity = 0;
              //counter = 0;
         public void Set(String name, final String num,
    float cost, int quantity)
         PartName = name;
         PartNumber= num;
         Cost = cost;
         Quantity = quantity;
         counter++;
         public float Get()
         return Cost*Quantity;
         public static int Counter() {return counter;}
    class PartCatalog
    {      public PartRecord[] Parts = new PartRecord[1000];
         public int npart;
    public PartCatalog()
    npart=0;
         public void Add(String name, String num,
         float cost, int quantity)
         if(npart>=1000) return;
         Parts[npart++].Set(name,num,cost,quantity);
         public float ShowInventory()
              float inventory = 0;
              for(int i=0; i<npart; i++)
              inventory= Parts[npart].Get();
              return inventory;
    /*class ExtPartCatalog extends PartCatalog
         public void Sort()
         Arrays.sort(Parts);
         public void Print()
                   for(int i=0; i<npart; i++)
                   System.out.println ( Parts.PartName + "\t "
                                  + Parts[i].PartNumber + "\t "
                                  + Parts[i].Cost + "\t "
                             + Parts[i].Quantity + "\n");
    class azimi_a{
    public static void main(String args[])
    PartCatalog c = new PartCatalog() ;//= new PartCatalog[4];
    c.Add("tire ", "1", 45, 200);
    c.Add("microwave", "2", 95, 10);
    c.Add("CD Player", "3", 215, 11);
    c.Add("Chair ", "4", 65, 10);
    <code>

  • Exception in thread "main" java.lang.NullPointerException error JDeveloper 12c

    Hello,
    I am trying to call a java stored procedure in java application. I am using ORACLE database and JDeveloper.
    I am getting error "Exception in thread "main" java.lang.NullPointerException. I have no idea what have I been doing wrong.
    I have a table "Beer" and I want to select all the data out with a stored procedure which I call out of Java app.
    I have a java.class file Store_A.java which I have loaded into the ORACLE database with LOADJAVA :
        import java.sql.*;
        import java.io.*;
        public class Store_a {
          public static void apskatit ()
            throws SQLException
            { String sql =
              "SELECT * FROM Beer";
            try { Connection conn = DriverManager.getConnection("jdbc:default:connection:");
              PreparedStatement pstmt = conn.prepareStatement(sql);
              ResultSet rset = pstmt.executeQuery();
              rset.close();
              pstmt.close();
            catch (SQLException e) {System.err.println(e.getMessage());
    Then I have created a procedure which I plan to call out in java:
        CREATE OR REPLACE PACKAGE Store_a AS
        PROCEDURE apskatit;
        END Store_a;
        CREATE OR REPLACE PACKAGE BODY Store_a AS
        PROCEDURE apskatit AS LANGUAGE JAVA
        NAME 'Store_a.apskatit()';
        END Store_a;
    And I have a java file that I have created with JDeveloper 12c:
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        public class Class1 {
             * @param args
            public static void main(String[] args) throws SQLException {
                Connection conn = null;
                try {
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    //Izveidojam savienojumu
                    conn = DriverManager.getConnection("jdbc.oracle.thin:@localhost:1521", "SYSTEM", "asdasd");
                    // Izveidojam callable statement
                    CallableStatement stmt = conn.prepareCall("CALL Store_a.apskatit()");
                    ResultSet resul = stmt.executeQuery();
                    while (resul.next()) {
                        System.out.println(resul.getInt(1) + "\t" + resul.getString(2));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
    When I try to run the java file, I get this error "Exception in thread "main" java.lang.NullPointerException at client.Class1.main(Class1.java:29).
    So the line I get error in is "conn.close();"
    How to fix this?
    Thank you very much in advance.

    I am trying to call a java stored procedure in java application. I am using ORACLE database and JDeveloper.
    I am getting error "Exception in thread "main" java.lang.NullPointerException. I have no idea what have I been doing wrong.
    Maybe you haven't read it yet but I told you in your other thread what you were doing wrong and, step by step, how to address the problem.
    https://forums.oracle.com/thread/2611124
    I'm not going to repeat everything again just this one main piece of advice:
    Until you get you code working outside the database don't even bother trying to load it into the DB and create a Java stored procedure.
    You are trying to deal with too many different issues at the same time. Unless you solve your primary Java problem by fixing the code outside the DB you will have nothing but problems loading it into the DB.
    And just get rid of this line of code - you don't need it anymore and it hasn't been done like that for many years now:
    Class.forName("oracle.jdbc.driver.OracleDriver");

  • Problem about "Exception in thread "main" java.lang.NullPointerException"

    This is t error message once i run the file
    Exception in thread "main" java.lang.NullPointerException
    at sendInterface.<init>(sendInterface.java:64)
    at sendInterface.main(sendInterface.java:133)
    * @(#)sendInterface.java
    * @author
    * @version 1.00 2008/7/18
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.GridLayout;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.ListModel;
    import javax.swing.UIManager;
    import javax.swing.SwingConstants;
    import java.io.*;
    import java.sql.*;
    import java.net.*;
    public class sendInterface  /*implements ActionListener*/{
         JFrame frame = new JFrame();
         private Panel topPanel;
         private Panel sendMessagePanel;
         private Panel sendFilePanel;
         private JLabel senderID;
         private JLabel receiverID;
         private JLabel senderDisplay;
         private DefaultListModel receiverListModel = new DefaultListModel();
         private JList receiverID_lst = new JList(receiverListModel);
         private JRadioButton sendType;
         String userName;
         String[] userList = null ;
         int i=0;
         Connection con;     
        public sendInterface() {
             String ListName;
                 try
                     JFrame.setDefaultLookAndFeelDecorated( true );
              catch (Exception e)
               System.err.println( "Look and feel not set." );
           frame.setTitle( "Send Interface" );
             topPanel.setLayout( new GridLayout( 2 , 1 ) );                          //line 64*************************
             senderID = new JLabel( "Sender:", SwingConstants.LEFT );
             senderDisplay = new JLabel( "'+...+'", SwingConstants.LEFT );
             receiverID = new JLabel( "Receiver:", SwingConstants.LEFT);
    //         receiverID_lst = new JList( ListName );
              frame.add(senderID);
             frame.add(senderDisplay);
             frame.add(receiverID);
    //         frame.add(receiverListModel);
             frame.add(new JScrollPane(receiverID_lst), BorderLayout.CENTER);
             frame.setLocation(200, 200);
             frame.setSize(250, 90);
             frame.setVisible(true);
        public void setListName(String user)
             try{
                  userName = user;
                  Class.forName("com.mysql.jdbc.Driver");
                   String url = "jdbc:mysql://localhost:3306/thesis";
                   con = DriverManager.getConnection(url, "root", "");
                   Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                   ResultSet rs = stmt.executeQuery("select * from user where User_ID!= '" + userName + "'");
                   System.out.println("Display all results:");
                   while(rs.next()){
                      String user_id = rs.getString("User_ID");
                      System.out.println("\tuser_id= " + user_id );
         //             receiverListModel.addElement(user_id);
                        userList=user_id;
                        i++;
              }//end while loop
              receiverListModel.addElement(userList);
         catch(Exception ex)
    ex.printStackTrace();
         finally
    if (con != null)
    try
    con.close ();
    System.out.println ("Database connection terminated");
    catch (Exception e) { /* ignore close errors */ }
    public String getUserName()
         return userName;
    public String[] getUserList()
         return userList;
    public static void main(String[] args) {
    new sendInterface(); //line 133******************************************
    thank ur reply:D
    Edited by: ocibala on Aug 3, 2008 9:54 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    And where do you instantiate topPanel before you invoke setLayout?
    db

  • Exception in thread "main" java.lang.NullPointerException:....Suggestions?

    Exception in thread "main" java.lang.NullPointerException: Canvas3D: null GraphicsConfiguration
    at javax.media.j3d.Canvas3D.checkForValidGraphicsConfig(Canvas3D.java:963)
    at javax.media.j3d.Canvas3D.<init>(Canvas3D.java:1006)
    at HelloJava3Da.<init>(HelloJava3Da.java:16)
    at HelloJava3Da.main(HelloJava3Da.java:45)

    Hello, Can you paste your code here?
    I think you may miss the following
            GraphicsConfiguration config =
               SimpleUniverse.getPreferredConfiguration();
            Canvas3D canvas3D = new Canvas3D(config);Thanks & Regards
    <~ChaosCrisis~>

  • Help with arrays and Exception in thread "main" java.lang.NullPointerExcept

    Hi, I have been having trouble all day getting this array sorted and put into a new array. I think it is something simple with my nested loops in sortCityArray() that is causing the problem. Any help would be greatly appreciated. The error is thrown on line 99 at Highway.sortCityArray(Highway.java:99)
    import java.util.Scanner;
    import java.io.*;
    import java.util.Arrays;
    public class Highway
    private String[] listOfCities=new String[200];
    private City[] cityArray=new City[200];
    private City[] sortedCityArray=new City[200];
    private String city="";
    private String city2="";
    private String fileName;
    private City x;
    private int milesToNextCity;
    private int milesAroundNextCity;
    private int speedToNextCity;
    public Highway(String filename)
    String fileName=filename;//"I-40cities.txt";
           File myFile = new File(fileName);
           try {
           Scanner scan=new Scanner(myFile);
           for(int i=0; scan.hasNextLine(); i++){
           String city=scan.nextLine();
           String city2=scan.nextLine();
           int milesToNextCity=scan.nextInt();
           int milesAroundNextCity=scan.nextInt();
           int speedToNextCity=scan.nextInt();
                   if(scan.hasNextLine()){
              scan.nextLine();
           cityArray=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    //return cityArray;
    /*public City[] doCityArray(){
    File myFile = new File(fileName);
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
    String city=scan.nextLine();
    String city2=scan.nextLine();
    int milesToNextCity=scan.nextInt();
    int milesAroundNextCity=scan.nextInt();
    int speedToNextCity=scan.nextInt();
         if(scan.hasNextLine()){
              scan.nextLine();
    cityArray[i]=new City(city,city2,milesToNextCity,milesAroundNextCity,speedToNextCity);
    // System.out.println(cityArray[i].getCity());
    // System.out.println(cityArray[i].getNextCity());
    // System.out.println(cityArray[i].getLengthAB());
    // System.out.println(cityArray[i].getLengthAroundB());
    // System.out.println(cityArray[i].getSpeedAB());
    catch (Exception e) {
    System.out.println(e);
    return cityArray;
    public City[] sortCityArray(){
    sortedCityArray[0]=new City(cityArray[0].getCity(),cityArray[0].getNextCity(),cityArray[0].getLengthAB(),cityArray[0].getLengthAroundB(),cityArray[0].getSpeedAB());
    for(int j=0; j<cityArray.length; j++ )
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
    /*     for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[j].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[j+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    //     j++;
    System.out.println(sortedCityArray[0].getCity());
    System.out.println(sortedCityArray[0].getNextCity());
    System.out.println(sortedCityArray[0].getLengthAB());
    System.out.println(sortedCityArray[0].getLengthAroundB());
    System.out.println(sortedCityArray[0].getSpeedAB());
    System.out.println(sortedCityArray[1].getCity());
    System.out.println(sortedCityArray[1].getNextCity());
    System.out.println(sortedCityArray[1].getLengthAB());
    System.out.println(sortedCityArray[1].getLengthAroundB());
    System.out.println(sortedCityArray[1].getSpeedAB());
    System.out.println(sortedCityArray[2].getCity());
    System.out.println(sortedCityArray[2].getNextCity());
    System.out.println(sortedCityArray[2].getLengthAB());
    System.out.println(sortedCityArray[2].getLengthAroundB());
    System.out.println(sortedCityArray[2].getSpeedAB());
    System.out.println(sortedCityArray[3].getCity());
    System.out.println(sortedCityArray[3].getNextCity());
    System.out.println(sortedCityArray[3].getLengthAB());
    System.out.println(sortedCityArray[3].getLengthAroundB());
    System.out.println(sortedCityArray[3].getSpeedAB());
    System.out.println(sortedCityArray[4].getCity());
    System.out.println(sortedCityArray[4].getNextCity());
    System.out.println(sortedCityArray[4].getLengthAB());
    System.out.println(sortedCityArray[4].getLengthAroundB());
    System.out.println(sortedCityArray[4].getSpeedAB());
    return cityArray;
    /*public String[] listOfCities(){
    File myFile = new File("I-40cities.txt");
    try {
    Scanner scan=new Scanner(myFile);
    for(int i=0; scan.hasNextLine(); i++){
         String city=scan.nextLine();
         city=city.trim();
    scan.nextLine();
    scan.nextLine();
         listOfCities[i]=city;
         System.out.println(listOfCities[i]);
    catch (Exception e) {
    System.out.println(e);
    return listOfCities;
    public static void main(String args[]) {
    Highway h = new Highway("out-of-order.txt");
    h.sortCityArray();

    the ouput is perfect according to the print lines if I use (increase the int where j is in the loop manually by one) :
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[0].getNextCity().equals(cityArray.getCity())){
              sortedCityArray[0+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
              break;
         for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[1].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[1+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[2].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[2+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
              for(int i=0; i<cityArray.length ;i++)
              if(sortedCityArray[3].getNextCity().equals(cityArray[i].getCity())){
              sortedCityArray[3+1]=new City(cityArray[i].getCity(),cityArray[i].getNextCity(),cityArray[i].getLengthAB(),cityArray[i].getLengthAroundB(),cityArray[i].getSpeedAB());
         break;
    But I cant do this for 200 elements. Are the loops nested right?
    Edited by: modplan on Sep 22, 2008 6:49 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Exception in thread "main" java.lang.UnsupportedClassVersionError:

    when i run javac its works fine.when i run java.exe the problem occurs.my jre and other java package is a part of the file that i downloaded from sun.com. i tried to reinstall but i doesn`t help.
    Exception in thread "main" java.lang.UnsupportedClassVersionError: NullPointer (Unsupported major.min
    or version 49.0)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    plz help..

    Hi,
    I had the same problem. I got the sam advice about the 'two versions' story.
    I was running java programs for Java 1.5 under Win ME (please don't laugh). I then I upgraded to XP. I re-installed Java 1.5. Suddenlu those same programs that were running under ME won't run under XP. Getting the same message as above.
    I only had 1 (one) Java version installed. That was Jave 1.5
    The funny thing is that jsp pages that I created under ME still worked fine under XP without me doing anything to them
    I un-installed Jave 1.5, re-install it and what do you know? Everything is fine now?
    It's a strange, strange world we program in, Master Jack (taken from a hit song in the late 60's in SA - need I say more?)
    Phlip

  • HELP Needed with this error:   Exception in thread "main" java.lang.NoClass

    Folks,
    I am having a problem connecting to my MSDE SQL 2000 DB on a WindowsXP pro. environment. I am learning Java and writing a small test prgm to connect the the database. The code compiles ok, but when I try to execute it i keep getting this error:
    "Exception in thread "main" java.lang.NoClassDefFoundError: Test1"
    I am using the Microsoft jdbc driver and my CLASSPATH is setup correctly, I've also noticed that several people have complained about this error, but have not seen any solutions....can someone help ?
    Here is the one of the test programs that I am using:
    import java.sql.*;
    * Microsoft SQL Server JDBC test program
    public class Test1 {
    public Test1() throws Exception {
    // Get connection
    DriverManager.registerDriver(new
    com.microsoft.jdbc.sqlserver.SQLServerDriver());
    Connection connection = DriverManager.getConnection(
    "jdbc:microsoft:sqlserver://LAPTOP01:1433","sa","sqladmin");
    if (connection != null) {
    System.out.println();
    System.out.println("Successfully connected");
    System.out.println();
    // Meta data
    DatabaseMetaData meta = connection.getMetaData();
    System.out.println("\nDriver Information");
    System.out.println("Driver Name: "
    + meta.getDriverName());
    System.out.println("Driver Version: "
    + meta.getDriverVersion());
    System.out.println("\nDatabase Information ");
    System.out.println("Database Name: "
    + meta.getDatabaseProductName());
    System.out.println("Database Version: "+
    meta.getDatabaseProductVersion());
    } // Test
    public static void main (String args[]) throws Exception {
    Test1 test = new Test1();

    I want to say that there was nothing wrong
    with my classpath config., I am still not sure why
    that didn't work, there is what I did to resolved
    this issue.You can say that all you like but if you are getting NoClassDefFound errors, that's because the class associated with the error is not in your classpath.
    (For future reference: you will find it easier to solve problems if you assume that the problem is your fault, instead of trying to blame something else. It almost always is your fault -- at least that's been my experience.)
    1. I had to set my DB connection protocol to TCP/IP
    (this was not the default), this was done by running
    the
    file "svrnetcn.exe" and then in the SQL Server Network
    Utility window, enable TCP/IP and set the port to
    1433.Irrelevant to the classpath problem.
    2. I then copied all three of the Microsoft JDBC
    driver files to the ..\jre\lib\ext dir of my jdk
    installed dir.The classpath always includes all jar files in this directory. That's why doing that fixed your problem. My bet is that you didn't have the jar file containing the driver in your classpath before, you just had the directory containing that jar file.
    3. Updated my OS path to located these files
    and....BINGO! (that simple)Unnecessary for solving classpath problems.
    4. Took a crash course on JDBC & basic Java and now I
    have created my database, all tables, scripts,
    stored procedures and can read/write and do all kinds
    of neat stuff.All's well that ends well. After a few months you'll wonder what all the fuss was about.

  • Exception in thread "main" java.lang.NoSuchMethodError: main -- Help

    I am new to Java programming and I have been working out of a book trying to learn the language. I am working on a Ubuntu system using Eclipse. I get an error when I try to run this app. It is: Exception in thread "main" java.lang.NoSuchMethodError: main. I have Googled it and read different possible solutions, but none have helped. Can someone help me solve this?
    Here is the code for battleshipGameTestDrive.java:_
    import java.util.ArrayList;
    public class battleshipGameTestDrive
         public static void main(String[] args, ArrayList<String> locations)      
              int numOfGuesses = 0;
              boolean isAlive = true;
              GameHelper helper = new GameHelper();
              battleshipGame ship = new battleshipGame();
              for (int ctr = 1; ctr < 4; ctr++)
                   int randomNum = (int) (Math.random() * 5);          
                   locations.add(Integer.toString(randomNum));
                   ship.setLocationCells(locations);
              while (isAlive == true){
                   String userGuess = helper.getUserInput("Enter a number (1-7): ");
                   numOfGuesses++;
                   String result = ship.checkYourself(userGuess);
                   if (result.equals("kill")){
                        isAlive = false;
                        System.out.println("You took " + numOfGuesses + " guesses");
                   } // close result if
              }  //end while loop
         }// end of main
    }// end of battleshipGameTestDrive class
    Here is the code for the battleshipGame class.java:_
    import java.util.ArrayList;
    public class battleshipGame {
         private ArrayList<String> locationCells;
         public void setLocationCells(ArrayList<String> loc){
              locationCells = loc;
         public String checkYourself(String userInput){
              String result = "miss";          
              int index = locationCells.indexOf(userInput);
              if (index >= 0){
                   locationCells.remove(index);
                   if (locationCells.isEmpty()){
                        result = "kill";
                   }else{
                        result = "hit";
                   }// close if
              }// closer outer if
              return result;
         }     //close method
    }     //close class

    Hello,
    I saw your short message youe sent to someone who had a problem : Exception in thread "main" java.lang.NoSuchMethodError :main
    So I was thinking maybe you could help me I struggle with this code fro 3weeks, this is a code I save it later as
    import java.awt.*;
    import java.awt.event.*;
    class Party {
    public void makeInvitation(){
    Frame f = new Frame();
    Label l = new Label("Party at Tom's");
    Button b = new Button("Sure");
    Button c = new Button("Noo...");
    Panel p = new Panel();
    p.add(l);
    I write this code in Notepad++ than I save it as java file with looks like this : Java source file (*.java)
    - than in Command Prompt I write : javac Party.java as usual and it comes with this error below Exception in thread "main" .......
    I have no idea what's wrong with it.Can you help me
    Thank you in advance

  • "Exception in thread "main" java.lang.NumberFormatException"error..pls help

    Hi,
    I'm trying to run a program I've written but keeping getting this error:
    Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:994)
    at java.lang.Double.parseDouble(Double.java:482)
    at data.newLineToRead(data.java:21)
    at data.data(data.java:34)
    at train.main(train.java:86)
    I'm not quite sure where I'm going wrong.I've included the data class and train class.Could someone pls help me.
    Thanks a lot.
    Data Class:
    import java.io.*;
    import java.util.*;
    public class data{
            private static parameter par;
            private static double[][] x=new double[par.n()][par.D()];
            public static double[] t=new double[par.n()];
            public static void newLineToRead(String LineToRead,int n){
            int d=0;
            String stringToRead=new String();
                    for(int i=0;i<=LineToRead.length();i++){
                            StringTokenizer str = new StringTokenizer (stringToRead,"/t");
                            String[] strtemp = new String[str.countTokens()];
                                    while (str.hasMoreTokens()){
                                    x[n][d++] = Double.parseDouble(str.nextToken());
                                    d++;
                                    System.out.println(x[n][d++]);
                            stringToRead=new String();
                    t[n]=Double.parseDouble(stringToRead);
                    x[n][par.d()]=1.0;
            public static void data() throws IOException{
            DataInputStream in=null;
                    try{
                            in=new DataInputStream(new FileInputStream(par.f()));
                            for(int n=0;n<par.n();n++){
                            String LineToRead=in.readLine();
                                    if(LineToRead.length()==0){
                                            System.out.println("Remove empty lines");
                                    else{
                                            newLineToRead(LineToRead,n);
                    }finally{if(in!=null){in.close();}}
            public static double x(int n,int d){return x[n][d];}
            public static double t(int n){return t[n];}
    }Train Class
    import java.io.*;
    import java.util.*;
    public class train{
             private static parameter       par;
             private static data            dat;
             private static model           mod;
             private static response        resp;
             private static void error(String msg){
                    System.out.println(msg);
                    System.exit(1);
             private static void check(){
                if(par.f().length()==0)
                    error("No filename of input vectors!");
                if(par.n()==0)
                    error("No number of input vectors!");
                if(par.d()==0)
                    error("No number of input variables!");
                if(par.d()>par.D())
                    error("Dimension is larger than 100!");
              private static void usage(){
                System.out.println("Non-default parameters==========================");
                System.out.println("-f filename of input vectors");
                System.out.println("-n number of input vectors");
                System.out.println("-d number of input variables");
                System.out.println("Default parameters==========================");
                System.out.println("-R regularisation constant (must be positive and the default value is 0.0)");
                System.out.println("-S epsilon criterion for stopping a learning process (default value is 0.001)");
                System.out.println("-C maximum learning cycle (default value is 10000)");
                      public static void main(String[] argv){
                            if(argv.length==0){
                                    System.out.println("Command line is <Java [-cp path] train parameters>");
                                    usage();
                                    System.exit(1);
                            if(argv.length==1 && argv[0].equals("help")==true){
                                    usage();
                                    System.exit(1);
                            par.nin(0); par.din(0); par.Rin(0.0); par.Cin(10000); par.Sin(0.001);
    for(int i=0;i<argv.length;i++){
                                            if(argv.equals("-f")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.fin(argv[i+1]);
    i++;
    else if(argv[i].equals("-d")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.din(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-n")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.nin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-S")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Sin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-C")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Cin(Integer.parseInt(argv[i+1]));
    i++;
    else if(argv[i].equals("-R")==true){
    if((i+1)==argv.length)
    error("miss the para");
    par.Rin(Double.parseDouble(argv[i+1]));
    i++;
    else error("Unkown token");
    check();
    try {
    dat.data();
    }catch(IOException e) { System.err.println(e.toString()); }
    try {
    mod.model();
    }catch(IOException e) { System.err.println(e.toString()); }
    try {
    resp.record();
    }catch(IOException e){ System.err.println(e.toString()); }

    String stringToRead=new String();
                    for(int i=0;i<=LineToRead.length();i++){
                            StringTokenizer str = new StringTokenizer (stringToRead,"/t");
                            String[] strtemp = new String[str.countTokens()];
                                    while (str.hasMoreTokens()){
                                    x[n][d++] = Double.parseDouble(str.nextToken());
                                    d++;
                                    System.out.println(x[n][d++]);
                            stringToRead=new String();
                    t[n]=Double.parseDouble(stringToRead);
                    x[n][par.d()]=1.0;
            }Not sure exactly what you are trying to do above but...
    You are setting your String to an empty String with "new String()" and then parsing that empty String. Eventually, you are trying to parse a double from that empty String:
    t[n]=Double.parseDouble(stringToRead);Also, I cannot think of a reason to ever use "new String()" when you could just use:
    String myString = "";

  • Exception in thread "main" java.lang.OutOfMemoryError(please help me )

    Hi All
    here my java class trying to read a txt file(which is having size of 60MB).and putting each line into a Vector class. problem is ,upto certain number of line it is reading properly and putting into vector..after that it is giving error like Exception in thread "main" java.lang.OutOfMemoryError..what is the problem and how to rectify this one..anybody help me on this.
    actual situation is one txt is there in that 80 lakhs of lines of content is there..java file trying to read each line and put it into vector or stringbuffer and split it into two lines like key=value and put it into hashmap object.then finally iam creating new file(.properties) and writing these hashmap data on it. if you want clearly..please look into below code..
    package test.utf8; import java.io.*; import java.util.*; public class AssetUtils
    //static StringBuffer stringbuffer = new StringBuffer();
    public AssetUtils()
    public static void main(String args[]) throws IOException
    BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\list.txt")));
    Vector vector = new Vector(0x30D40, 50000);
    System.out.println(vector.capacity());
    Object obj = null;
    int n=0;
    System.out.println("Reading list:" + new Date(System.currentTimeMillis()));
    do
    String s = bufferedreader.readLine();
    //System.out.println("line no: "+ ++n);
    if(s == null)
    break;
    vector.add(s);
    } while(true);
    System.out.println("List Read complete:" + new Date(System.currentTimeMillis()));
    String s1 = args[0];
    System.out.println("S1: "+s1);
    System.out.println(vector.capacity());
    HashMap hashmap = new HashMap();
    System.out.println( "Vector.Size..>>>>>>>>>>>>>>>>.."+vector.size());
    for(int i = 0; i < vector.size(); i++)
    System.out.println("i value:"+i);
    String s2 = (String)vector.get(i);
    //System.out.println("S2: "+s2);
    if(s2.indexOf("/") != -1)
    String s3 = s2.substring(s1.length(), s2.length());
    //System.out.println("S3: "+s3);
    if(s3.indexOf("/") != -1) {
    String s4 = s3.substring(0, s3.lastIndexOf("/"));
    //System.out.println("S4: "+s4);
    String s6 = s3.substring(s3.lastIndexOf("/") + 1, s3.length());
    //System.out.println("S6: "+s6);
    StringBuffer stringbuffer=null;
    stringbuffer = new StringBuffer();
    String s8 = (String)hashmap.get(s4);
    //System.out.println("S8: "+s8);
    if(s8 != null) stringbuffer.append(s8 + "," + s6);
    else
    stringbuffer.append(s6);
    hashmap.put(s4, stringbuffer.toString());
    //stringbuffer.delete(0,stringbuffer.length());
    stringbuffer=null;
    System.out.println("Opening asset.properties:" + new Date(System.currentTimeMillis()));
    File file = new File("D:\\asset.properties");
    PrintWriter printwriter = new PrintWriter(new FileOutputStream(file));
    String s5;
    String s7;
    for(Iterator iterator = hashmap.keySet().iterator(); iterator.hasNext(); printwriter.println(s5 + "=" + s7))
    { s5 = (String)iterator.next(); s7 = (String)hashmap.get(s5); } printwriter.close();
    System.out.println("Closing asset.properties:" + new Date(System.currentTimeMillis()));

    Theres a number of ways you can improve your memory usage:
    1) Build you map as you read in your file.
    2) Use StringBuffers in your map - do not use "asshaj" + "ashaskj" This is very memory intensive
    If you still run out of memory try running the JVM using -Xms128m -Xmx512m or higher

  • Help me solving this exception: Exception in thread "main" java.lang...

    Dear,
    I have "test" class:
    public class test{
    public static void main(String argv[]){
    System.out.println("Hello world!");
    I use below command to compiler & run this class:
    C:\> javac test.java
    There is no problem and I get file: test.class
    After that, I use:
    C:\> java test
    I meet this message and the class cannot be run:
    Exception in thread "main" java.lang.NoClassDefFoundError: test
    Please help me to solve this problem.
    Regards,
    Cuong Ha

    before running set classpath
    like this type in command prompt
    suppose this class file in in folder c:\abc
    set classpath=%classpath%;C:\abc\
    and now run ur code
    or
    i think this is better solution not try aboce try this first
    before running
    type this
    set path=%path%;c:\jdk1.3\bin
    where 'c:\jdk1.3\bin' is the path where ur jdk is installed

  • Aspectj with JVM is giving Exception in thread "main" java.lang.NoSuchMetho

    Dear Forum Experts,
    I have installed JDK and Aspectj in C:\Program Files\Java\jdk1.5.0_03. I wrote a aspect to trace my program. i compiled using ajc -argfile Temp/tracev1.lst.
    compiled fine..but i ran my aspect using command..C:\..\jdk1.5.0_03\java Temp.version1.TraceMyClasses
    i'm getting error..Exception in thread "main" java.lang.NoSuchMetho
    i should get tracing of all stack trace in format: return type:Package:Methods: Signatures
    My Class paths are as follows:
    classpath
    set PATH=%PATH%;C:\Program Files\Java\jdk1.5.0_03\bin;
    JAVA_HOME
    C:\Program Files\java\jdk1.5.0_03
    PATH
    C:\Program Files\java\jdk1.5.0_03\bin
    I Burst out from it..Plz help me out in this..
    Regards
    Raj

    What method does it say that it can't find?
    You might just need to make sure that your compilation of all files is up to date. If you remove a method from one file and recompile only that file, and then you try to call the old method from a file that hasn't been recompiled, you will get that error. If you had tried to recompile the second file, it wouldn't have compiled, because of the removed method.

Maybe you are looking for