Home > Back-end >  Any other way to loop through rows without hard-coding in Java?
Any other way to loop through rows without hard-coding in Java?

Time:03-16

My main focus is around the area where it says (split[*number*], shift);

I would like to use as little hard coding as possible, yet I can't figure out a way around this.

I am aware that, with Scanner, you can use .next() or .nextLine() to go to the next line, but this time I am looping through a very long String[], where I need every seven rows to represent a single person.

while(scanner.hasNext()) {
    Person person = new Person();
    Address address = new Address();

    // Decrypts "DELIM" by 'shift' times
    String decrDelim = action.encrypt("DELIM", shift);

    String linesFromFile = scanner.nextLine();
    String[] split = linesFromFile.split(decrDelim);

    String decrFirstName, decrLastName, decrSignature;
    String decrAddress, decrZipcode, decrCity;
    int decrHeight;

    // Reads the 7 first rows of the file and decrypts them
    decrFirstName = action.decrypt(split[0], shift);
    decrLastName = action.decrypt(split[1], shift);
    decrSignature = action.decrypt(split[2], shift);
    decrHeight = Integer.parseInt(action.decrypt(split[3], shift));

    decrAddress = action.decrypt(split[4], shift);
    decrZipcode = action.decrypt(split[5], shift);
    decrCity = action.decrypt(split[6], shift);

    // Stores all 7 rows in object variables
    person.setFirstName(decrFirstName);
    person.setLastName(decrLastName);
    person.setSignature(decrSignature);
    person.setHeight(decrHeight);

    address.setAddress(decrAddress);
    address.setZipcode(decrZipcode);
    address.setCity(decrCity);

    person.setAddress(address); // Collects all elements from Address and attaches to Person
    listFromFile.add(person); // Adds complete person to ArrayList 'newList'

    //action.verifySignature(person); // Checks and assigns all signatures
}

CodePudding user response:

You can use an Iterator over the array to avoid having to write the array indices explicitly:

String[] split = linesFromFile.split(decrDelim);
Iterator<String> parts = Arrays.asList(split).iterator();

decrFirstName = action.decrypt(parts.next(), shift);
decrLastName = action.decrypt(parts.next(), shift);
// And so on.

CodePudding user response:

Because you want to store the data in the Person object so I think it's the only way to have the People list. You can try with 2-dimensional array for storing the data depending on your calculation need afterward.

  • Related