user1805445
user1805445

Reputation: 159

Resetting character when end is reached java

Take following code as base:

for (int i = 0; i < 26; i++)
{   
    alphabet[i] = (char) ('A'+  i );
}

My question is: -

If 'A' Changes to 'X' how can we achieve the alphabet to reset from the start?

For example XYZABC

Upvotes: 1

Views: 181

Answers (2)

cello
cello

Reputation: 5486

Whenever you have something that should "wrap around", have a look at the modulo operator. The basic idea is: you don't want to count from i=0 to 26, but e.g. from i=23 to 49, but only add the modulo-26 value to it.

Instead of starting to count at 23 (which would be kind of 'X' - 'A'), you can directly integrate this offset into your loop:

for (int i = 0; i < 26; i++)
{   
    alphabet[i] = (char) ('A' + ('X' - 'A' +  i) % 26);
}

'A' is the base, 'X' - 'A' builds that offset where you add i to, and then take the modulo of 26 (as the alphabet has 26 characters), and then add that to your 'A' again.

Upvotes: 2

MC Emperor
MC Emperor

Reputation: 23027

You can just insert an if statement:

char startChar = 'X';

for (int i = 0; i < 26; i++) {
    char ch = (char) (startChar + i);
    if (ch > 'Z') {
        ch -= 26;
    }
    alphabet[i] = ch;
}

Upvotes: 2

Related Questions