1

I have a column in a table that contains numeric values. However, some fields are empty. I want to read all fields in this column into integer variable. How should I manage empty fields?

int total = tableModel.getValueAt(currentRow, currentCol).toString().equals("") ? 0 : Integer.parseInt(tablePaxModel.getValueAt(currentRow, currentCol).toString());
3
  • how about just reading the value as String first. then check for nulls or blanks and finally parse to appropriate int. for example you can put 0 where ever you see null. also, where does this int go? can a default value for null or blank affect any other calculations? Commented Oct 27, 2015 at 16:15
  • @AbtPst: I think that my solution is what you suggest. Am I right? I just wanted to be sure that the way I'm doing it is correct. Blanks can only affect "total". Commented Oct 27, 2015 at 16:16
  • correct, that is the straightforward way to do it. as long as you put a default value lie 0, it should not affect any additions that you are doing. Commented Oct 27, 2015 at 16:18

2 Answers 2

2
     try 
     {
        String valueInCell = (String)tablePaxModel.getValueAt(currentRow, currentCol);

        if(valueInCell == null || valueInCell.isEmpty())
        {
            valueInCell = "0";
        }

        int tempCellValue = Integer.parseInt(valueInCell);

        total += tempCellValue;

    } catch (Exception e) 
    {
        e.printStackTrace();  
    }
Sign up to request clarification or add additional context in comments.

Comments

0
something like

try {
    String val = tablePaxModel.getValueAt(currentRow, currentCol).toString();

    int temp=0;
    if(val.isEmpty() || val == null)
       temp=0;

    else
    {
    temp = Integer.parseInt(val);
    }

    total = total + temp
}

catch (Exception e) 
    {
        e.printStackTrace();  
    }

something like that. i have taken some assumptions with your code but you can modify as needed

1 Comment

Also, "temp" needs to be changed otherwise it will always be 0 unless you assign it. int temp has the default value of 0, so even if the value is null or empty, its always adding zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.