Java encryption project (java.lang.StringIndexOutOfBoundsException)

72 Views Asked by At
import java.util.Scanner;
public class Oppish_Coder2 {

    public static void main(String[] args) {
        String s = "bcdfghjklmnpqrstvwxz";
        String ss = "aeiouy";

        System.out.println("Enter line to encrypt: ");

        Scanner sc = new Scanner (System.in);
        String uncoded = sc.next();

        System.out.println("Encrypted line: ");

            for (int i = 0; i < uncoded.length(); i++){

                for (int ii = 0; ii < s.length(); ii++){

                    if (uncoded.charAt(i) == s.charAt(ii)){
                        System.out.print(uncoded.charAt(i) + "op ");
                    }
                    else {
                        for (int iii = 0; iii < ss.length(); iii++){
                            if (uncoded.charAt(i) == ss.charAt(ii)){
                                System.out.print(uncoded.charAt(i) + " ");
                            }
                        }
                    }   
                }
            }
        sc.close();
    }
}

I've been working on this project for fun on and off but recently I feel as if I'm very close to getting it to work however an error is being thrown and I'm not sure about how to fix it. The purpose of the code is to add an "op " to the end of any consonants and a " " to the end of vowels. This was inspired by a childhood way of talking in code so only you and a friend knew what the other was saying. Any help would be greatly appreciated, Thanks!

1

There are 1 best solutions below

0
On

You don't need to loop so many times for checking whether a character in your uncoded string is a vowel or consonant.

I've simplified your program by using String.indexOf method. You just check whether the letters in your uncoded string are present in the vowels string or consonants string.

Here it is:

import java.util.Scanner;

public class Oppish_Coder2 {

    public static void main(String[] args) {
        String consonants = "bcdfghjklmnpqrstvwxz";
        String vowels = "aeiouy";

        System.out.println("Enter line to encrypt: ");

        Scanner sc = new Scanner(System.in);
        String uncoded = sc.next();

        System.out.println("Encrypted line: ");

        for (int i = 0; i < uncoded.length(); i++) {
            char c = uncoded.charAt(i);
            if (consonants.indexOf(c)>-1) {
                System.out.print(c + "op ");
            } else if (vowels.indexOf(c)>-1) {
                System.out.print(c + " ");
            }
        }
        sc.close();
    }
}

Hope this helps!