【发布时间】:2017-02-16 14:48:28
【问题描述】:
我希望我的代码采用我的.txt 文件的第一行并以某种方式打印它,我认为我的想法是正确的,但控制台内没有发生任何事情。
这是我的.txt 文件:
ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO
12345678912345678912345678912
这是我的.java 文件:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
int iterator = 0;
char[][] table = new char[6][5];
// fill array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
table[i][j] = line.charAt(iterator++);
}
}
// print array
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
我希望我的代码只从我的.txt 文件中取出第一行并像这样打印出来:
ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO
这是我收到的error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 29
at java.lang.String.charAt(String.java:686)
at EncryptDecrypt.encrypt(EncryptDecrypt.java:14)
at EncryptDecrypt.main(EncryptDecrypt.java:28)
【问题讨论】:
-
您遇到了什么问题?你试过用调试器运行它吗?
-
尝试用
try-catch包围您的代码,看看是否抛出了任何I/O 错误,这也是一个好习惯。 -
复制您的加密方法代码并创建一个像您一样的文件,它对我来说按预期工作。
-
@ThomasBöhm 由于某种原因它对我不起作用
-
真的要删除每六个字符吗?因为看起来你每次都在倒数第二行旁边这样做,所以没有缺少字符。
标签: java algorithm for-loop encryption