samedi 24 octobre 2020

Access string using charAt and loops

I'm working on an assignment. We are given a decryption key as a string and are told to use charAt and character.isLetter.

This is an exercise in loops and accessing strings. I'm confused because the assignment makes it seem like it should be only a couple of lines of code, but without converting the strings to arrays I'm not sure how that's possible.

I tried to set up a loop which doesn't work:

for (i=0; i<len; i++) {
        letter=userInput.charAt(i);
        if (letter == alphabet.charAt(i)) {
        alphabet = alphabet + decryptKey;
        decryptKey = alphabet.substring(0, alphabet.length()-decryptKey.length());
        letter = decryptKey.charAt(i);
        System.out.print(letter);

I had a problem with counter, as I wanted it to iterate for the length of the userInput string, but also I wanted another counter (and loop) to make sure the program ran through the length of the alphabet to check characters.

I want it to say: if letter is the same as alphabet.charAt(iteration), letter is the same index at decryptKey.charAt(iteration). Print letter.

Even if I put for, while, or if loops I couldn't get it beyond the first letter because the condition was met, even if I added another counter.

I'm confused. Am I abusing what charAt does? Should I be setting either a series of if loops or case/switch statements instead?

I'm planning on doing this assignment with arrays, too, but we haven't studied that yet.

Any help would be appreciated, thanks!

Aucun commentaire:

Enregistrer un commentaire