Search code examples
javaarrayscharbufferedreader

Read a String from a txt file and store it into a char array in java


I am new to java. I am trying to read a text file and store the variables it into an array char by char then apply Caesar Cipher encryption to it. However I am getting ejava.lang.StringIndexOutOfBoundsException: String index out of range: 4 on the line that says if (str.charAt(i) == str.charAt(j)) If someone could help ,that would be great!

PROBLEM SOLVED*

public void passwordCaesaCipher() throws Exception {
        String str;
        int size = 0;
        char[] string1 = {};
        File f = new File("password.txt");
        BufferedReader br = new BufferedReader(new FileReader(f));
        String lowercase = "abcdefghijklmnopqrstuvwxyz";

        while ((str = br.readLine()) != null) {
            System.out.println(str);
            string1 = str.toCharArray();
            size = str.length();
            System.out.println(size);
            System.out.println(string1);
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < 26; j++) {
                    if (str.charAt(i) == lowercase.charAt(j)) {
                        System.out.print(str.charAt((j) % 26));
                    }
                    else
                    {
                        
                    }

                }
            }
            System.out.println();

        }

    }

My text file has "abc" and I want it to be "bcd". However with my implementation I am getting abc.


Solution

  • Editing the second loop helped me to achieve the correct answer. I forgot to add +1 to System.out.print(lowercase.charAt((j) % 26));. Because of that it was just printing itself . Correct solution is: System.out.print(lowercase.charAt((j+1) % 26));