In the Java method, modulo division does not work correctly,I can't understand what the problem is

Task:write a groupify method that accepts two parameters. The first parameter is the string that you want to split into groups. The second argument is the number of letters in the group.Example: calling groupify(“HITHER”, 2) should give the result: "HI TH ER".If the last group is not equal to the previous one, add "x" to the end of the line.Example: calling groupify(“HITHERE”, 2) should give the result: “HI TH ER Ex”. I wrote the code,and it copes with the first part of the task,the problem is adding "x".I added a check:

if (list.size() % num !=0){
    list.add('x');
    }

But for some reason, this condition is always fulfilled, whether it is false or not, although by the condition "x" should be added only when there is a remainder in the division.That's the problem.Here is the entire code:

public static void groupify(String word,int num){
        char input[] = word.toCharArray();
        ArrayList list = new ArrayList();
        int number = num;

        for (int i = 0; i < input.length; i++) {
            if (i == number) {
                list.add(' ');
                list.add(input[i]);
                number += num;
            } else {
                list.add(input[i]);
            }
        }

        if (list.size() % num !=0){
            list.add('x');
        }
       System.out.println(list);
    }

That's it, I figured it out, instead of dividing by the modulus of the array with already added spaces and the input number

if (list.size() % num !=0){
            list.add('x');
        }

Made the division modulo the input string and the input number

if (word.length() % num !=0){
            list.add('x');
        }

Now everything works as it should.

Author: Zebsier, 2018-05-29

1 answers

groupify("HITHERE", 2);

static void groupify(String word, int num){
    if(num <= word.length()){
       int startPos = 0;
        for(int i = 0; i < word.length() / num; i++){
            System.out.println(word.substring(startPos, startPos += num));
        }
        if(word.length() %num != 0){
            System.out.println(word.substring(word.length() - 1) + "x");
        } 
    }else{
        System.err.println("incorrect num variable");
    }
}

Conclusion:

HI
TH
ER
Ex

After slightly correcting the code, you can add it to an array or collection instead of printing it, and print it as output.

 1
Author: Pollux, 2018-05-29 23:26:55