Mastouri Maha
Mastouri Maha

Reputation: 19

put some values in a for loop in an array

I am filtering a file rows with an if condition and I need to make a new array which containing only the values that satisfy the condition.

I can get them in the console but I don't know how to assign them to a table, can anyone help me please?

String section_title;
for (int j=11; j<row_num; j++) 
{
    Row row = (Row) rowIterator.next();
    Cell s0 = sheet.getRow(j-1).getCell(0);
    if(s0.toString()!="" )
    {
        section_title = s0.toString();
        d  = j-1;    
        System.out.println(d);
     }
}

Upvotes: 0

Views: 61

Answers (2)

tquadrat
tquadrat

Reputation: 4034

The goal is to scan some input and to get an array of int as a result. As we do not know the final number of entries for the array, we should use something with a variable length for that purpose. Usually, this would be a List of some kind, but List is not defined for int (or other primitives), only for object types like Integer. So we would need a transformation step after collecting the numbers.

Since Java 8, we have Streams, and with that, the problem can be solved more directly:

String section_title;
var builder = IntStream.builder();
for( var j = 11; j < row_num; ++j ) 
{
    var row = (Row) rowIterator.next();
    Cell s0 = sheet.getRow( j - 1 ).getCell( 0 );
    if( !s0.toString().isEmpty() )
    {
        section_title = s0.toString();
        builder.add( Integer.valueOf( j - 1 ) );
     }
}

var array = builder.build().toArray();

System.out.println( array );

Under the hood, this solution may end up to be nearly the same as one using Collections. But it still looks neater.

Upvotes: 0

Zachary Oldham
Zachary Oldham

Reputation: 868

Consider using an arraylist object to hold those values.

It would look something like this:

String section_title;
ArrayList<int> list = new ArrayList<int>();  // instanciate the array list
for (int j=11; j<row_num; j++) 
{
    Row row = (Row) rowIterator.next();
    Cell s0 = sheet.getRow(j-1).getCell(0);
    if(s0.toString()!="" )
    {
        section_title = s0.toString();
        d  = j-1;    
        list.add(d);  // Add d to the list
     }
}

System.out.println(list);  // Print the final list

Upvotes: 1

Related Questions