Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java - Variablies being null.

Options
  • 17-01-2010 9:45pm
    #1
    Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭


    Here is a part of my code stripped down for a question. I am booking hops of a train journey by selecting them in a jlist. If I select one hop an object of size one is made, this will store the hop... ie "sligo galway"...two hops...object of size two is made
    "sligo galway"
    "galway limerick"
    etc.

    This works fine when I book a one hop journey or a two hop journey but if I try to book a three hop journey (len ==3) the variables hop2start and hop2end are assigned null for some reason, whilst the other variables are assigned correctly. Object[1] however does contain the correct data so I do not know why the tokenized strings of what it contains are null?


    So if the hops are like so in the object:

    sligo galway
    galway limerick
    limerick cork

    they are assigned to variables as:

    sligo galway null null limerick cork


    I know it's something simple because if I just tokenize object[1] again inside the second (len == 3) statement the variables are assigned the correct data.
    try {
                Object[] object = PossibleTrips.getSelectedValues();
               
    
                int len = Array.getLength(object);
    
                String lol = "" + object[0];
                StringTokenizer hop = new StringTokenizer(lol);
                hop1start = hop.nextToken();
                hop1end = hop.nextToken();
    
                if (len == 2) {
                    String lol1 = "" + object[1];
                    StringTokenizer objA = new StringTokenizer(lol1);
                    hop2start = objA.nextToken();
                    hop2end = objA.nextToken();
                    
                } else if (len == 3) {
                    String lol2 = "" + object[2];
                    StringTokenizer objB = new StringTokenizer(lol2);
                    hop3start = objB.nextToken();
                    hop3end = objB.nextToken();
                }
    
    
                tixnum = "" + (tickets.getSelectedValue());
    
                if (len == 1) {
    
                    Statement statement = connection.createStatement();
    
    
                    String sqlQuery = "SELECT TrainID FROM trainsystem.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop1start + "' and `Arrival`='" + hop1end + "'";
             
                    ResultSet rr = statement.executeQuery(sqlQuery);
                    rr.next();
                  
                    TrainID = "" + (rr.getString("TrainID"));
                    out.println("Booking" + " " + tixnum + " " + hop1start + " " + hop1end + "  " + booktime + " " + canceltextdata + " " + TrainID);
    
    
                    } else if (len == 2) {
                        
                    Statement statement = connection.createStatement();
    
    
                    String sqlQuery = "SELECT TrainID FROM trainsystem.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop1start + "' and `Arrival`='" + hop1end + "'";
                    System.out.println(sqlQuery);
                    ResultSet rr = statement.executeQuery(sqlQuery);
                    rr.next();
                    TrainID = "" + (rr.getString("TrainID"));
    
                    out.println("Booking" + " " + tixnum + " " + hop1start + " " + hop1end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                    System.out.println("Booking" + " " + tixnum + " " + hop1start + " " + hop1end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                    out.close();
    
                  
    
                    MyClient = new Socket("xps-nds-11", port + 1);
                    out = new PrintWriter(MyClient.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(MyClient.getInputStream()));
    
                    statement = connection.createStatement();
                    String sqlQuery2 = "SELECT TrainID FROM trainsystem.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop2start + "' and `Arrival`='" + hop2end + "'";
                   
                    ResultSet rs = statement.executeQuery(sqlQuery2);
    
                   
                    if (rs.next()) {
    
                       
                        TrainID = "" + (rs.getString("TrainID"));
    
    
                        out.println("Booking2" + " " + tixnum + " " + hop2start + " " + hop2end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                        System.out.println("Booking2" + " " + tixnum + " " + hop2start + " " + hop2end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                    } else {
                        System.out.println("no train id");
                    }
    
    
                    } else if (len == 3) {
    
                      
                  
                    Statement statement = connection.createStatement();
    
    
                    String sqlQuery = "SELECT TrainID FROM serverdb.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop1start + "' and `Arrival`='" + hop1end + "'";
                    ResultSet rr = statement.executeQuery(sqlQuery);
                    rr.next();
    
                    TrainID = "" + (rr.getString("TrainID"));
                    
                    out.println("Booking" + " " + tixnum + " " + hop1start + " " + hop1end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                   
                    out.close();
    
    
                    MyClient = new Socket("xps-nds-11", port + 1);
                    out = new PrintWriter(MyClient.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(MyClient.getInputStream()));
    
    
                    statement = connection.createStatement();
                    String sqlQuery2 = "SELECT TrainID FROM trainsystem.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop2start + "' and `Arrival`='" + hop2end + "'";
    
                    ResultSet rs = statement.executeQuery(sqlQuery2);
                       
    
                    if (rs.next()) {
    
    
                        TrainID = "" + (rs.getString("TrainID"));
                      
    
    
    
                        out.println("Booking2" + " " + tixnum + " " + hop2start + " " + hop2end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                        System.out.println("Booking2" + " " + tixnum + " " + hop2start + " " + hop2end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                        out.close();
    
                        MyClient = new Socket("xps-nds-11", port + 1);
                        out = new PrintWriter(MyClient.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(MyClient.getInputStream()));
    
                          }
                        statement = connection.createStatement();
                        String sqlQuery3 = "SELECT TrainID FROM trainsystem.trainoperator where `DepartureTime` = '" + booktime + "' and `Departure` = '" + hop2start + "' and `Arrival`='" + hop2end + "'";
                        
                        ResultSet rt = statement.executeQuery(sqlQuery3);
    
                      
                        if (rt.next()) {
    
                           
                            TrainID = "" + (rt.getString("TrainID"));
                           
    
                            out.println("Booking3" + " " + tixnum + " " + hop3start + " " + hop3end + "  " + booktime + " " + canceltextdata + " " + TrainID);
                            System.out.println("Booking3" + " " + tixnum + " " + hop3start + " " + hop3end + "  " + booktime + " " + canceltextdata + " " + TrainID);
    
                        }
    
                   } else {
                       System.out.println("no train id etc");
    
                   }
    
    
    
    
    
    
                }
    


Comments

  • Registered Users Posts: 1,916 ✭✭✭ronivek


                if (len == 2) {
                    String lol1 = "" + object[1];
                    StringTokenizer objA = new StringTokenizer(lol1);
                    hop2start = objA.nextToken();
                    hop2end = objA.nextToken();
                    
                } else if (len == 3) {
                    String lol2 = "" + object[2];
                    StringTokenizer objB = new StringTokenizer(lol2);
                    hop3start = objB.nextToken();
                    hop3end = objB.nextToken();
                }
    

    Well the first problem is the above should probably be changed to:

    [PHP]
    if (len >= 2) {
    String lol1 = "" + object[1];
    StringTokenizer objA = new StringTokenizer(lol1);
    hop2start = objA.nextToken();
    hop2end = objA.nextToken();

    }
    if (len == 3) {
    String lol2 = "" + object[2];
    StringTokenizer objB = new StringTokenizer(lol2);
    hop3start = objB.nextToken();
    hop3end = objB.nextToken();
    }
    [/PHP]

    As it stands you're only instantiating hop2 if your array is of length two; so when it's of length three the if statement isn't executed.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    Whoops yeah, I had a print statement as a test in the wrong loop I found out...hazards ofthe 13th hour of programming!

    Thanks very much, don't need my crap workaround now.


  • Closed Accounts Posts: 228 ✭✭gnxx


    Nulls are the source of all evil in Java.

    If you have the ability to test for a value, always take it. For example, use the contains method for maps.

    In your example, you should use the StringTokenizer.hasMoreTokens() method.

    Here is some rough code ... very rough ...

    String[] values = ....

    StringTokenizer stk = new StringTokenizer( values );

    Map<String,String> m = new HashMap<String,String>();

    while ( stk.hasMoreTokens() ) {

    String key = stk.nextToken();

    if ( stk.hasMoreTokens() == false ) {
    throw new IllegalStateException("no value for key [" + key + "]");
    }

    String value = stk.nextToken();

    map.put(key, value);

    }

    for ( String k : map.keyset() ) {
    String v = map.get( k );
    System.out.println(k +" " + v);

    }


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    One more question about my bad coding skills.

    Below if I get a two hop trip it assigns a value to bookingid in the (one.equals("Booking")) if statement, and then runs the next (one.equals("Booking2")) if statement.
    In this loop a value is assigned to bookingid2 and an attempt is made to sent back both bookingids over the socket. However only bookingid2 and null are sent. bookingid is null in the second loop, why does bookingid not retain a value in the second statement?
    I can send it back in the first statement no problem

     public synchronized void queries() {
            try {
                try {
                    out = new PrintWriter(clientSocket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    
    
                    line = in.readLine();
                  
                    StringTokenizer st = new StringTokenizer(line);
                    System.out.println(line);
                    String one = st.nextToken();
                    String two = st.nextToken();
                    String three = st.nextToken();
                    String four = st.nextToken();
                    String five = st.nextToken();
                    String six = st.nextToken();
                    String seven = st.nextToken();
                    if (one.equals("Booking")) {
                        try {
                            Statement statement = connection.createStatement();
                            ResultSet r = statement.executeQuery("select SeatsAvail from serverdb.trainoperator WHERE Departure = '" + three + "'  and  Arrival = '" + four + "'and  TrainID = '" + seven + "'");
                            if (r.next())
                            {
                           
                            
                            Seats = r.getInt("SeatsAvail");
                           
                             int seatsordered = Integer.parseInt(two);
                            if (Seats < seatsordered) {
                                String errormsg = "NoTickets";
                                out.println("nextsocket" + " " + errormsg);
                            } else  {
                               connection.setAutoCommit(false);
                                statement.executeUpdate("UPDATE trainoperator SET SeatsAvail = Seatsavail - '" + two + "' WHERE Departure = '" + three + "'  and  Arrival = '" + four + "' and TrainID ='" + seven + "'");
                                statement.executeQuery("set @unique = UUID()");
                                statement.executeUpdate("INSERT into bookingtable (TicketNum, BookingNum, DepartureStation, ArrivalStation, TrainID)values('" + two + "', @unique,'" + three + "','" + four + "','" + seven + "');");
                               // statement.executeUpdate("commit;");
                                connection.commit();
                                //else connection.rollback();
                                ResultSet rs = statement.executeQuery("SELECT * from bookingtable where BookingNum = @unique;");
                                rs.next();
    
                                bookingid = rs.getString("Bookingnum");
                          
                                 System.out.println("it works:" + bookingid);
                                
                            out.println("it worksSSS:" +" "+ bookingid);
                            }
                            }
                             else {
    
                            out.println("nextsocket1");
                            }
            
                ResultSet RS = statement.executeQuery("SELECT * from addroute");
                RS.next();
    
                  do
                  {  //System.out.println(RS.getString("NewDeparture") + (RS.getString("NewArrival") + RS.getString("Weight") + RS.getString("OperatorNum") + (RS.getString("Trainid"))));
                     out.println("AddRoutes:"+" "+RS.getString("NewDeparture")+" " + (RS.getString("NewArrival")+ " " + RS.getString("Weight") + " " + RS.getString("OperatorNum")+ " " + (RS.getString("Trainid")+ " " + bookingid)));
                      
                  }
                     while
                    (RS.next());
    
       
    
                            
                        } catch (SQLException ex) {
                            Logger.getLogger(serverapp.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        
                    }
    
                    if (one.equals("Booking2")) {
                       
                        try {
                            System.out.println("come on");
                           Statement statement = connection.createStatement();
                            ResultSet r = statement.executeQuery("select SeatsAvail from trainoperator WHERE Departure = '" + three + "'  and  Arrival = '" + four + "'and  TrainID = '" + seven + "'");
                          if ( r.next())
                            
                            {
                            Seats = r.getInt("SeatsAvail");
                          
    
    
                                int seatsordered = Integer.parseInt(two);
    
    
                            if (Seats < seatsordered) {
                                String errormsg = "NoTickets";
                                out.println("NoTicket:" + " " + errormsg);
                            } else {
    
                                statement.executeUpdate("UPDATE trainoperator SET SeatsAvail = Seatsavail - '" + two + "' WHERE Departure = '" + three + "'  and  Arrival = '" + four + "' and TrainID = '" + seven + "'");
                                statement.executeQuery("set @unique = UUID()");
                                statement.executeUpdate("INSERT into bookingtable (TicketNum, BookingNum, DepartureStation, ArrivalStation, TrainID)values('" + two + "', @unique,'" + three + "','" + four + "','" + seven + "');");
                                ResultSet rs = statement.executeQuery("SELECT * from bookingtable where BookingNum = @unique;");
                                rs.next();
                                String packet = "a";
                                String packet2="b";
                                String packet3="c";
                                bookingid2 = rs.getString("Bookingnum");
                               
                                out.println("BookingID2:" + " " + bookingid2+" " +bookingid + " "+packet3+" " +packet +" "+ packet2 + " "+packet3);
    
                            }
                          
                        }
    


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    gnxx wrote: »
    Nulls are the source of all evil in Java.

    If you have the ability to test for a value, always take it. For example, use the contains method for maps.

    In your example, you should use the StringTokenizer.hasMoreTokens() method.

    Here is some rough code ... very rough ...

    String[] values = ....

    StringTokenizer stk = new StringTokenizer( values );

    Map<String,String> m = new HashMap<String,String>();

    while ( stk.hasMoreTokens() ) {

    String key = stk.nextToken();

    if ( stk.hasMoreTokens() == false ) {
    throw new IllegalStateException("no value for key [" + key + "]");
    }

    String value = stk.nextToken();

    map.put(key, value);

    }

    for ( String k : map.keyset() ) {
    String v = map.get( k );
    System.out.println(k +" " + v);

    }

    Amen! They driving me a crazzzzzzy.

    Thanks, I will try that in future! I knwo the way i do things is quite bad at the moment, practice..practice.


  • Advertisement
  • Closed Accounts Posts: 228 ✭✭gnxx


    Amen! They driving me a crazzzzzzy.

    Thanks, I will try that in future! I knwo the way i do things is quite bad at the moment, practice..practice.

    No problem.


  • Registered Users Posts: 1,916 ✭✭✭ronivek


    There's some evil nesting going on in there :)

    It seems like the same issue as before. You have two mutually exclusive conditionals. You're only setting the value of one once, therefore you'll only ever execute one if block for one execution of that method. Either you execute the first conditional block if one.equals("Booking") or you execute the second block if one.equals("Booking2").

    You're then accessing bookingid in the second conditional block; which is only instantiated in the first conditional block. As a result it will always be null.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    It's pretty nasty stuff all right! Much more that I don't show, oh the looping!

    They are meant to be exclusive... I send out two strings, the head of one will be booking, the head of the other will be booking2.
    What I do is book the first hop by sending values over the socket, then book the second hop by sending more values over the socket.

    So I instantiate it...send another string(booking2) and thought it would still retain the value, obviously not!

    Is their any way for me to store bookingid so that when the second loop runs it can get that value..before it returns to null or whatever it does?


    Thanks :)


  • Registered Users Posts: 1,916 ✭✭✭ronivek


    Hmm well its scope is greater than that one method call so in theory it should retain the value. Are you using multiple threads? Are you sure you're not setting that variable somewhere else in between iterations?


  • Closed Accounts Posts: 228 ✭✭gnxx


    I hate to lecture but will offer the following tips ..

    1. Break your code into method calls and keep methods to a single "function" -- this extends to classes in larger programmes; these can be easily tested for expected input and output. You can also write the template of the entire program very quickly and then just fill in the methods afterwards

    2. Use lists/generics and avoid arrays

    3. Make sure that nulls don't screw you ... keep them out of code

    4. Throw an IllegalStateException when the unexpected happens so you are not tearing your hair out looking for strange errors

    So for some examples,

    Say with your routing information:

    // accepts a string such as tralee dublin dundalk and makes a list
    // the starting point is always first
    private List<String> createJourney(String[] objects) {
    if ( objects == null ) {
    throw new IllegalStateException("createJourney passed a null");
    }

    List<String> result = new LinkedList<String>();

    StringTokenizer stk = new StringTokenizer ( objects[0] );

    while ( stk.hasNext() ) {
    result.add( stk.nextToken() );

    }

    if ( result.size() == 0 ) {
    throw new IllegalStateException("journey with no dest " + result.get(0));
    }
    return result;
    }


    public void doSQL( List<String> input ) {

    String query;

    if ( input.size() == 2 ) {
    query = "SELECT * from XXX where
    } else if ( input.size() = 3 ) {
    query = "SELECT * from XXX wher"
    } else {
    throw new IllegalStateException("input has wrong size (" + input.size+ ")";
    }



    }


  • Advertisement
  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,098 Mod ✭✭✭✭Tar.Aldarion


    ronivek wrote: »
    Hmm well its scope is greater than that one method call so in theory it should retain the value. Are you using multiple threads? Are you sure you're not setting that variable somewhere else in between iterations?
    I am using threads insofar that multiple clients applicationscan connect to the server, that's it. I don't think I am setting it somewhere else, i'll hanve another look. It's been annoying me for weeks...but I've been putting off figuring it out in favour of other stuff.
    gnxx wrote: »
    I hate to lecture but will offer the following tips ..

    1. Break your code into method calls and keep methods to a single "function" -- this extends to classes in larger programmes; these can be easily tested for expected input and output. You can also write the template of the entire program very quickly and then just fill in the methods afterwards

    2. Use lists/generics and avoid arrays

    3. Make sure that nulls don't screw you ... keep them out of code

    4. Throw an IllegalStateException when the unexpected happens so you are not tearing your hair out looking for strange errors

    So for some examples,

    Say with your routing information:

    // accepts a string such as tralee dublin dundalk and makes a list
    // the starting point is always first
    private List<String> createJourney(String[] objects) {
    if ( objects == null ) {
    throw new IllegalStateException("createJourney passed a null");
    }

    List<String> result = new LinkedList<String>();

    StringTokenizer stk = new StringTokenizer ( objects[0] );

    while ( stk.hasNext() ) {
    result.add( stk.nextToken() );

    }

    if ( result.size() == 0 ) {
    throw new IllegalStateException("journey with no dest " + result.get(0));
    }
    return result;
    }


    public void doSQL( List<String> input ) {

    String query;

    if ( input.size() == 2 ) {
    query = "SELECT * from XXX where
    } else if ( input.size() = 3 ) {
    query = "SELECT * from XXX wher"
    } else {
    throw new IllegalStateException("input has wrong size (" + input.size+ ")";
    }



    }
    Thanks, very nice of you to make the effort, lecture by all means!
    My programming skills are not the best. It's good to see better methods.


  • Registered Users Posts: 1,916 ✭✭✭ronivek


    I am using threads insofar that multiple clients applicationscan connect to the server, that's it. I don't think I am setting it somewhere else, i'll hanve another look. It's been annoying me for weeks...but I've been putting off figuring it out in favour of other stuff.

    Are you using a thread pool of shared objects or instantiating a new object for each client?

    For example what could be happening is your ServerSocket is accepting a connection from a client who wants "Booking2" before it accepts any connection from a client who wants "Booking". As your queries method is synchronised then once the client who wants "Booking2" gets a lock on the object then a sequence of instructions will never occur whereby uniqueid will not be null.


Advertisement