简体   繁体   English

从 txt 文件中读取字符串并将其存储到 java 中的 char 数组中

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

I am new to java.我是 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!但是我得到了 ejava.lang.StringIndexOutOfBoundsException: String index out of range: 4 在说if (str.charAt(i) == str.charAt(j))如果有人可以提供帮助,那就太好了!

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".我的文本文件有“abc”,我希望它是“bcd”。 However with my implementation I am getting abc.但是,通过我的实现,我得到了 abc。

You might want to check the length for the 2nd for loop that is 26. When the string that you read from the file is less than 26 of length, it will always result to index out of range.您可能需要检查第二个 for 循环的长度为 26。当您从文件中读取的字符串长度小于 26 时,总是会导致索引超出范围。

Editing the second loop helped me to achieve the correct answer.编辑第二个循环帮助我获得了正确的答案。 I forgot to add +1 to System.out.print(lowercase.charAt((j) % 26));我忘了给System.out.print(lowercase.charAt((j) % 26));添加 +1 . . Because of that it was just printing itself.正因为如此,它只是在打印自己。 Correct solution is: System.out.print(lowercase.charAt((j+1) % 26));正确的解决方案是: System.out.print(lowercase.charAt((j+1) % 26));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM