繁体   English   中英

线程主ArrayIndexOutOfBoundsException中的异常

[英]Exception in thread main ArrayIndexOutOfBoundsException

有人可以帮助我解决以下错误。 线程主java.lang.arrayindexoutofboundsexception中的异常:RowTrans.encrypt(Rowtrans.java:33)处为3在RowTrans.main(Rowtrans.java:7)处

在我的程序中,我想获取一条文本。 将其放在具有5列的矩阵中,并根据文本的长度确定行。 然后,我想更改列和行的位置,以便行获得列的位置,而列获得行。 当一行不包含5个值时,我想在空白处添加字符Z。 任何人都可以帮助我解决这个错误。

这是我的代码

import java.util.Scanner;

public class ColTrans {

   public static void main(String[] args)
   {
      String ori = "This is my horse";
      String enc = encrypt(ori);
      System.out.println(enc);
      // String dec = decrypt(enc);
      // System.out.println(dec);
   }

   static String encrypt(String text)
   {
      String result = "";
      text = text.toUpperCase();
      int length = text.length();
      int rows = length / 5;
      char[][] b = new char[rows][5];
      char[][] c = new char[5][rows];
      char[] d = new char[length];
      if ((length % 5) != 0)
         rows = rows + 1;

      int k = 0;
      for (int i = 0; i < rows; i++)
         for (int j = 0; j < 5; j++)
         {
            if (k > length)
               b[i][j] = 'Z';
            else
            {
               d[k] = text.charAt(k);
               b[i][j] = d[k];
            }

            k++;
         }

      for (int i = 0; i < 5; i++)
         for (int j = 0; j < rows; j++)
         {
            c[i][j] = b[j][i];
            result = result + c[i][j];
         }

      return result;

   }
}

原因如下:

一旦定义了数组,您将使行变量无动于衷。

将下一行移动到char [][] b =new char[rows][5];

if ((length % 5) != 0)

      rows = rows + 1;

您的代码中有2个问题。 首先将mod部分移到矩阵实例化之前:

  if ((length % 5) != 0)
     rows = rows + 1;

   char [][] b =new char[rows][5];
   [...]

然后将if ( k > length )更改为if ( k >= length )

只需更改您的代码,如下所示:

if ((length % 5) != 0)
   rows = rows + 1;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];

根据您的描述:

text = text.toUpperCase();
    char[] b = text.toCharArray();
    char[][] c = new char[b.length][5];

    int bLen = 0;
    for (int i = 0; i < c.length; i++) {
        for (int j = 0; j < 5; j++) {
            if(bLen < b.length)
                c[i][j] = b[bLen++];
            else
                c[i][j] = 'Z';

        }
    }

 //change the column and row position 
 char[][]d = new char[c[0].length][c.length];

    for (int i = 0; i < d.length; i++) {
        for (int j = 0; j < d[0].length; j++) {
            d[i][j] = c[j][i];

        }
    }

输出: TI EZZZZZZZZZZZZHSHZZZZZZZZZZZZZI OZZZZZZZZZZZZZSMRZZZZZZZZZZZZZ YSZZZZZZZZZZZZZ

暂无
暂无

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

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