2017-12-15 1 views
0

키워드 기수 암호에 대한 작업을하고 있으며 배열 예외가 계속 발생합니다. 코드 디버깅을 시도하고 문제를 이해하려고 시도했지만 catch 할 수 없습니다. ! 나는에 예외를 받고 있어요for-loop에서 2d 배열 out-of-bound 예외가 발생했습니다.

public Decryption (String cipherText, String keyWord) { 

     cipherText = cipherText.replaceAll("\\s+",""); 
     cipherText = cipherText.toUpperCase(); 
     cipherText = cipherText.trim(); 

     keyWord = keyWord.toUpperCase(); 

     int column = keyWord.length(); 

     int row = (cipherText.length()/keyWord.length()); 
     if (cipherText.length() % keyWord.length() != 0) 
      row += 1; 

     char [][] matrix = new char [row][column]; 

     int re = cipherText.length() % keyWord.length(); 
     for (int i = 0; i < keyWord.length() - re; i++) 
     matrix[row - 1][keyWord.length() - 1 - i] = '*'; 

     char[] sorted_key = keyWord.toCharArray(); 
     Arrays.sort(sorted_key); 

     int p = 0, count = 0; 
     char[] cipher_array = cipherText.toCharArray(); 

     Map<Character,Integer> indices = new HashMap<>(); 

     for(int i = 0; i < column; i++){ 

     int last = indices.computeIfAbsent(sorted_key[i], c->-1); 
     p = keyWord.indexOf(sorted_key[i], last+1); 
      indices.put(sorted_key[i], p); 

      for(int j = 0; j < row; j++){ 
      if (matrix[j][p] != '*') 
      matrix[j][p] = cipher_array[count]; 
        count++; 
       }} 
} 

: 나는 그것이 나에게 예외를 제공하지 않습니다 J = 1로 시작하는 경우

matrix[j][p] = cipher_array[count]; 

는 루프에 문제가 있지만 난 몰라

YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWU을 :

내가 해독하기 위해 노력하고있어 암호문을 (그것은 마지막 행을 인쇄되지 않음) 정확한 결과를 얻을 수 NGEFUOLNDRDEYGOOAOJRUCKESPY

키워드 :

자신에게

내가 1 루프를 시작할 때 내가 얻을 결과 : 당신의 배경 지식에 대한

판사 자신이 CRYP

을 이해하기
내가 도착하기로되어있어 무엇3210

:

판사 자신을 당신의 배경 지식에 대한 정보 코드 나던 날이 유효성을 검사 할 수 있기 때문에 나는 정확하게 확실하지 않다 암호를

+1

여기에이 방법을 따라

코드의 고정 된 버전 (변경된 부분에 대한 코드의 주석을 확인을)입니다 코드의 들여 쓰기가 읽기 쉽도록 질문을 수정하십시오. –

+0

코드가 컴파일되지 않습니다. 실행 가능한 코드를 게시하십시오. – seokgyu

+0

게시 한 코드가 제대로 작동하도록 조정되었습니다. 메소드의 마지막에'System.out.println (Arrays.deepToString (matrix));'을 추가하면'matrix'가 괜찮음을 알 수 있습니다. 문제는 아마도'print' 프로세스에있을 것입니다. – OldCurmudgeon

답변

0

을 이해하기 (가)의 파고가없는 알고리즘의 출력을 확인하는 쉬운 방법이 없기 때문에 ... 나는 해결책이 가정

for (int j = 0; j < row; j++) { 
      if (matrix[j][p] != '*'){ 
       matrix[j][p] = cipher_array[count]; 
       count++; 
      } 
     } 

대신 :

for (int j = 0; j < row; j++) { 
       if (matrix[j][p] != '*') 
        matrix[j][p] = cipher_array[count]; 
        count++; 

      } 
0

이 경우 문자열에 '*'를 추가하는 전략은 당신이 한 것과 같은 방식이 아니라고 생각합니다. 그리드를 만들 때 문자를 추가하는 것이 좋습니다. 당신이 이것을 실행하면

import java.util.Arrays; 
import java.util.HashMap; 
import java.util.Map; 

public class Decryption { 

    private final String result; 

    public Decryption(String cipherText, String keyWord) { 

     cipherText = cipherText.replaceAll("\\s+", ""); 
     cipherText = cipherText.toUpperCase(); 
     cipherText = cipherText.trim(); 

     keyWord = keyWord.toUpperCase(); 

     int column = keyWord.length(); 

     int row = (cipherText.length()/keyWord.length()); 
     if (cipherText.length() % keyWord.length() != 0) 
      row += 1; 

     int[][] matrix = new int[row][column]; 

     // Changed to calculate the irregular columns 
     int re = column - (row * column - cipherText.length()); 

     char[] sorted_key = keyWord.toCharArray(); 
     Arrays.sort(sorted_key); 

     int p, count = 0; 
     char[] cipher_array = cipherText.toCharArray(); 

     Map<Character, Integer> indices = new HashMap<>(); 

     for (int i = 0; i < column; i++) { 

      int last = indices.computeIfAbsent(sorted_key[i], c -> -1); 
      p = keyWord.indexOf(sorted_key[i], last + 1); 
      indices.put(sorted_key[i], p); 

      // Changed: Detects the need of an extra character and fills it in case of need 
      boolean needsExtraChar = p > re - 1; 
      for (int j = 0; j < row - (needsExtraChar ? 1 : 0); j++) { 
       matrix[j][p] = cipher_array[count]; 
       count++; 
      } 
      if(needsExtraChar) { 
       matrix[row - 1][p] = '-'; 
      } 
     } 

     result = buildString(matrix); 
    } 

    public static void main(String[] args) { 
     System.out.println(new Decryption("EVLNE ACDTK ESEAQ ROFOJ DEECU WIREE", "ZEBRAS").result); 
     System.out.println(new Decryption("EVLNA CDTES EAROF ODEEC WIREE", "ZEBRAS").result); 
     System.out.println(new Decryption("YARUEDCAUOADGRYHOBBNDERPUSTKNTTTGLORWUNGEFUOLNDRDEYGOOAOJRUCKESPY", "YOURSELF").result); 
    } 

    private String buildString(int[][] grid) { 
     return Arrays.stream(grid).collect(StringBuilder::new, (stringBuilder, ints) -> Arrays.stream(ints).forEach(t -> { 
      stringBuilder.append((char) t); 
     }), (stringBuilder, ints) -> { 
     }).toString().replace("-", ""); 
    } 
} 

,이 인쇄됩니다 :

WEAREDISCOVEREDFLEEATONCEQKJEU 
WEAREDISCOVEREDFLEEATONCE 
JUDGEYOURSELFABOUTYOURBACKGROUNDKNOWLEDGETOUNDERSTANDCRYPTOGRAPHY