Mee Mee - 1 year ago 71
Java Question

How to compare a string to an array?

I am trying to compare a string to an array but it doesn't seem to work and showing this exception...

Exception in thread "main" java.lang.NullPointerException
at ReadCol.main(

My code is shown below...

public String[] array;
ResultSet rs=st.executeQuery("select * from ATTENDANCE");

File file = new File("E:\\eclipse\\workspace\\AutoAttendanceSystem\\res\\AttendanceData.csv");
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
array = line.split(",");
if(rs.getString(1).equals(array[0]) && rs.getString(7).equals(array[6])){
JOptionPane.showMessageDialog(null, "Can't Update Because record already exist");

how can I do the comparison?

Answer Source

It appears that the problem is when you call rs.getString(7).equals(...) : a NULL value must have been stored in the 7th column, and getString(7) returns null, which is why calling equals on null throws an exception.

It could as well be on the first column too. If you want to know, separate the conditions on 2 lines and see which one throws an exception :

if(rs.getString(1).equals(array[0]) && 

If it is ok for your database to hold NULL values, then what you should do, is test for it before applying equals :

if( ( rs.getString(1) == null && array[0] == null // or "" if you prefer
    || rs.getString(1) != null && rs.getString(1).equals(array[0]) )
    && ... // same for 7th column

To make it cleaner :

String databaseResult1, databaseResult2, fileResult1, fileResult2;

databaseResult1 = rs.getString(1);
fileResult1 = array[0];
databaseResult2 = rs.getString(7);
fileResult2 = array[6];

    ( databaseResult1 == null && fileResult1 == null 
      || databaseResult1 != null && databaseResult1.equals(fileResult1) )
    ( databaseResult2 == null && fileResult2 == null 
      || databaseResult2 != null && databaseResult2.equals(fileResult2) )

By the way, you are not comparing a String to an Array, you are comparing two Strings (which is the right thing to do)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download