0

I need to write a message and then change every letter by another following a certain number

Ex: if my message is abcd and the number chosen is 5 then my message has to become fghi.

I simply created a for loop going through the table char and created a table containing all the letter of the alphabet and a switch case for every letter. I thought this was like python, and i could loop to the beginning of my table, but it tells me that the index is out of bound. what are my possibilities?

char[] abc = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        for (int i = 0; 1 <= mesgIn.length; i++){
            switch(mesgIn[i]) {
                case 'a' -> mesgIn[i] = mesgIn[rot];
                case 'b' -> mesgIn[i] = abc[1 + rot];
                case 'c' -> mesgIn[i] = abc[2 + rot];

edit: int rot is the number of letter rotation i want to do. equals to wtv the user wants

edit 2: found an easier to do it. i simply added the alphabet twice in abc[], so abc[0] is 'a', but so is abc[26]

Avunz
  • 1
  • 1

2 Answers2

0

The index starts at 0 in a String so the last index is the length of the string minus 1. Thus, the terminating condition of the loop should be i < mesgIn.length(). Also, you can perform an arithmetic operation with char values just like you do with int values.

public class Main {
    public static void main(String args[]) {
        char[] abc = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
                't', 'u', 'v', 'w', 'x', 'y', 'z' };
        String mesgIn = "wxyz";
        int n = 5;
        for (int i = 0; i < mesgIn.length(); i++) {
            System.out.print((char) ((mesgIn.charAt(i) - 'a' + n) % 26 + 'a'));
        }
    }
}

Output:

bcde
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

You can also use some standard data structures with well-defined methods.

import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    String[] messages = {"abc", "xyz"};
    int rot = 5;
    List<Character> alphabets =
        Arrays.asList(
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    for (String message : messages) {
      for (int i = 0; i < message.length(); i++) {
        char originalChar = message.charAt(i);
        int indexInAlphabets = alphabets.indexOf(originalChar);
        System.out.print(alphabets.get((rot + indexInAlphabets) % alphabets.size()));
      }
      System.out.print("\n");
    }
  }
}

Output

fgh
cde
Tushar
  • 670
  • 3
  • 14