簡體   English   中英

在 Java 中運行此代碼時出現數組越界錯誤

[英]Array out of bounds error when running this code in Java

我在下面有以下代碼,它不斷給我一個 ArrayIndexOutOfBoundsException 錯誤。 我似乎無法發現錯誤的來源。 我知道 for 循環有問題,但它沒有出現在我身上。 我試圖將字符 1 空格從原始數組向右移動到新數組。 任何幫助表示贊賞。 謝謝。

import java.util.Arrays;
public class HW3_1N {
 static final int ROWS = 8;
 static final int COLS = 16;

 public char[][] shiftChars(char newAr[][]) {
  char[][] x = new char[ROWS][COLS];
  for (int i = 0; i < newAr.length; i++) {
   for (int j = 0; j < newAr[i].length; j++) {
    if (newAr[i][j] < (char) 32 || newAr[i][j] > (char) 126) {

     x[i][j] = (char) 32;
    } else if (j >= newAr[i].length) {
     int lastchar = newAr[i].length;
     x[i][lastchar] = newAr[i][0];
     break;

    } else if (newAr[i][j] > (char) 32 || newAr[i][j] < (char) 126 || j < newAr[i].length) {
     int added = j + 1;
     x[i][j] = newAr[i][added];

    }
   }
  }
  return x;
 }


 public static void main(String[] args) {
  char[][] array = new char[ROWS][COLS];
  for (int i = 0; i < array.length; i++)
   for (int j = 0; j < array[i].length; j++)
    array[i][j] = (char)(i * COLS + j);

  System.out.println("Original Array of characters:");
  System.out.println("_______________________________");
  for (int i = 0; i < array.length; i++) {
   for (int j = 0; j < array[i].length; j++)
    if (array[i][j] < (char) 32 || array[i][j] > (char) 126)
     System.out.print("" + '\u0240' + ' ');
    else
     System.out.print("" + array[i][j] + ' ');
   System.out.println();
  }
  System.out.println("_______________________________");
  char[][] result = null;
  HW3_1N o = new HW3_1N();
  result = o.shiftChars(array);

  System.out.println("\n\nNew Array from shiftChars(): ");
  System.out.println("_______________________________");
  for (int i = 0; i < array.length; i++) {
   for (int j = 0; j < array[i].length; j++)
    if (result[i][j] < (char) 32 || result[i][j] > (char) 126)
     System.out.print("" + '\u0240' + ' ');
    else
     System.out.print("" + result[i][j] + ' ');
   System.out.println();
  }
  System.out.println("_______________________________");
 }

}

問題出在線路上

int added = j + 1;

因此,在循環結束時,您正在索引 (j + 1)th element ,因此越界異常。 循環應該運行到

int j = 0; j < newAr[i].length-1; j++ 

但由於這會改變您的輸出,您只需設置

      if (j < newAr[i].length-1){
          added = j+1;
      }
      else{
          added = 0;
      }
 x[i][added] = newAr[i][j];

這是你的原創

這是您更新的,沒有任何移位的列和數組完好無損

新形狀的陣列具有完整的方向,我希望這是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM