【问题标题】:Why won't my first line be printed from my txt file?为什么我的第一行不能从我的 txt 文件中打印出来?
【发布时间】: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


【解决方案1】:

您的输出与您想要的输出不同(因为它有效),因为您没有过滤每 6 个字符。我认为这就是你想要这样做的......

我想我通过使用模数找到了您的解决方案,您可以搜索每 6 个数字。即 6 % 6 = 0 而 5 % 6 = 1

// fill array
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 5; j++) {
            if ((iterator + 1) % 6 == 0) {
                iterator++;
                j--;
            } else {
                //System.out.println(i+" "+ j + " " +iterator + " " + line.charAt(iterator));
                char t = line.charAt(iterator++);
                table[i][j] = t;
            }
        }
    }

还要在字符串中添加 2 个字符。 line.charAt(iterator++) 正在搜索 java.lang.StringIndexOutOfBoundsException。这就是您收到错误的原因

【讨论】:

    【解决方案2】:

    原生的substring() 方法可以帮助你处理一些条件和增量

            String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
    
            int ite = str.length() / 5;
            int i = 0, j = 0;
    
            while ( i < ite ) {
    
                System.out.println( str.substring( j, ( j += 5 ) ) );
                i++;
            }
    
            System.out.println( str.substring( ite * 5, str.length() % 5 + ite * 5 ) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多