Home » Java » java – For-loop prints only the last value of Array through whole Excel file-Exceptionshub

java – For-loop prints only the last value of Array through whole Excel file-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am struggling through this IBAN Checker JAVA project where I am supposed to take IBANs from an excel sheet -> validate them -> print valid/invalid results back into Excel. I have it almost all set up but now I got stuck on looping function that should put already validated IBANS back to the sheet. Here I am getting only last IBAN number of my IBAN Array which gets printed into all the rows, other IBANs are not showing.

However, when I use “System.out.printf(“%s is %s.%n”, iban, validateIBAN(iban) ? “valid” : “not valid”);” function all the ibans are validated correctly and printed into console one by one.

Is there please some way to get the results of above “System.out.printf” and iterate them through the cells in the Excel sheet? Or would you have some suggestion for modifications of the for-loop please? I think something in the loop is causing the issue because when I put “System.out.prinf” function inside of the loop, it starts validating only the last IBAN number which means something with the loop is not right.

Thank you very much for any help you can give!

IBANChecker03.java
package ibanchecker03;

import java.math.BigInteger;
import java.util.*;


//EXCEL
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//EXCEL


public class IBANChecker03 {



 private static final String DEFSTRS = ""
            + "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 "
            + "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 "
            + "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 LB28 LI21 "
            + "LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 "
            + "PS29 PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 "
            + "TN24 TR26 AE23 GB22 VG24 GR27 CR21";
    private static final Map<String, Integer> DEFINITIONS = new HashMap<>();

    static {
        for (String definition : DEFSTRS.split(" "))
            DEFINITIONS.put(definition.substring(0, 2), Integer.parseInt(definition.substring(2)));
    }


    public static void printValid(String iban) throws FileNotFoundException, IOException, InvalidFormatException{


           File file=new File("G:\AR\INVprint (GD Thomas)\EKG.xls");
           FileInputStream ExcelFile = new FileInputStream(file);
            HSSFWorkbook wb = new HSSFWorkbook(ExcelFile);
                HSSFSheet sheet = wb.getSheet("SheetF");



         System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid");



try {

                for(int rowNumber = 0; rowNumber < sheet.getLastRowNum(); rowNumber++) {


                     HSSFRow row1 = sheet.getRow(rowNumber);
                        HSSFCell cell = row1.createCell(1);


                      cell.setCellValue(iban + " is " + validateIBAN(iban));
                         //System.out.println(cell); 


                        //for(int columnNumber = 1; columnNumber < row1.getLastCellNum();) {
                       // HSSFCell cell = row1.createCell(columnNumber);


                       //  if(cell != null) {

                            //cell.setCellValue("Darkness");
                            //System.out.println(cell);


                        }
         // Write the output to a file

                        FileOutputStream fileOut = new FileOutputStream("G:\AR\INVprint (GD Thomas)\EKG.xls");



                           wb.write(fileOut);
                         wb.close();

           } catch(FileNotFoundException e) {


                throw new FileNotFoundException ("File not faaund");
           }




        }





     public static void main(String[] args) throws IOException, FileNotFoundException {




        String[] ibans = {"GB33BUKB20201555555555"};
        for(String iban : ibans){
            try {
                printValid(iban);



            } catch (InvalidFormatException ex) {
                Logger.getLogger(IBANChecker03.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }


    static boolean validateIBAN(String iban) {
        iban = iban.replaceAll("\s", "").toUpperCase(Locale.ROOT);

        int len = iban.length();
        if (len < 4 || !iban.matches("[0-9A-Z]+") || DEFINITIONS.getOrDefault(iban.substring(0, 2), 0) != len)
            return false;

        iban = iban.substring(4) + iban.substring(0, 4);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++)
            sb.append(Character.digit(iban.charAt(i), 36));

        BigInteger bigInt = new BigInteger(sb.toString());

        return bigInt.mod(BigInteger.valueOf(97)).intValue() == 1;

        }

}


HomeOffice.java
package ibanchecker03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class HomeOffice {

    public static void main(String[] args) throws Exception {


       File excelFile= new File("G:\AR\INVprint (GD Thomas)\TEST2 IBAN.xlsx");

       FileInputStream fis=new FileInputStream(excelFile);


       XSSFWorkbook workbook=new XSSFWorkbook(fis);

       XSSFSheet sheet=workbook.getSheetAt(0);



       //Here we start iterating through raws and cells

       Iterator<Row> rowIt=sheet.iterator();

       while(rowIt.hasNext()){
           Row row=rowIt.next();

       Iterator<Cell> cellIterator=row.cellIterator();

       while(cellIterator.hasNext()){

       Cell cell=cellIterator.next();


       if(cell.getColumnIndex()==7){      // Choose number of column 

      //System.out.println(cell.toString() + ","); // Print cells


        String cellvalue = cell.toString();


        IBANChecker03.printValid(cellvalue);








    }


    }

    workbook.close();

    fis.close() ;  

        }          

    }   

  }
How to&Answers: