|
-
January 26th, 2003, 03:30 PM
#1
Java programming puzzle
Here's something I ran into while writing some java code. Th question is, why will the following code not run and how would you fix it? I'll post the solution as a hidden post tomorrow. Also, anyone who posts a solution, please post it as hidden.
These are the conditions under which the program is run:
1) The DSN is called test
2) The table is called test
3) The table has a column 'STRING' that has less than a 100 rows
4) The column 'STRING' has some NULL values
5) The column 'STRING' also has some values that are equal to blank Strings (represented as "" by Java
6) *HINT* There are no compile-time errors in the program. If there are, fix them as they are bound to be fairly simple to fix (I haven't tested this code, but it's almost a copy-paste of the same code from a different program.
7) the_JinX is not allowed to participate in the puzzle as he already has the fixed code .
8) If you are copy-pasting this code, in the 12th line remove the space after the first : . I had to put it in there as otherwise AO displays it like this .
Code:
import java.sql.*;
class Test
{
String stringArray[]=new String[100];
Connection con;
Statement stm;
Resultset rs;
Test() throws SQLException, ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc: odbc:test"); //test is the name of the Data Source
stm=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stm.executeQuery("select STRING from test"); //test is the name of a table
for(int i=0,j=0;rs.next();i++)
{
if(rs.getString("STRING")!=null || !rs.getString("STRING").equals(""))
{
stringArray[j]=rs.getString("STRING");
j++;
}
}
}
}
Best of luck!!
Cheers,
cgkanchi
-
January 27th, 2003, 01:22 PM
#2
Solution
Since no one seems to have the solution to this question, here it is:
1) The code
Code:
if(rs.getString("STRING")!=null || !rs.getString("STRING").equals(""))
{
stringArray[j]=rs.getString("STRING");
j++;
}
will not run for the reason that when rs.getString("STRING")==null, the comparison rs.getString("STRING").equals("") will generate a java.lang.NullPointer exception as parameter being passed to String.equals(String) is a null value and NOT a String.
2) To fix this, the code should read:
Code:
if(rs.getString("STRING")!=null)
{
if(!rs.getString("STRING").equals(""))
{
stringArray[j]=rs.getString("STRING");
j++;
}
}
Cheers,
cgkanchi
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|