2013-05-16 1 views
2

문자 배열 [4] [4]가 있습니다. 'a'와 나는 배열의 열을 다른 문자열과 비교하기위한 문자열로 저장하려고합니다. 하지만 문제는 문자열에 원래 요소를 계속 추가한다는 것입니다. 아래 코드는 배열에 "car"& "trip"이라는 단어를 포함하고 있으며이 단어를 다른 문자열과 비교하여 사실로 만듭니다.비교를 위해 char 배열 열을 문자열에 저장합니다.

char[][] puzzle = {{'a', 'c', 'h' ,'t'}, 
        {'v', 'a', 'x', 'r'}, 
        {'x', 'r', 'e', 'i'}, 
        {'c', 'q', 'i', 'p'} 
        }; 

for(int row=0; row<puzzle.length; row++) 
{ 

    String match = ""; 
    String matchword =""; 
    for(int col=0; col<puzzle.length; col++) 
    { 
    match += puzzle[col][row]; 
    System.out.print(match); 
    } 
System.out.println(); 
} 

은 다음 문자열로 출력 될 때 : aavavxavxc ccacarcarq hhxhxehxei ttrtritrip

대신 :

어떤 도움을 여행 hxei carq avxc 여기 내 코드입니다 대단히 감사하겠습니다.

답변

0

문제는 루프 반복마다 매치를 인쇄하는 것입니다.

루프가 완료되면 인쇄해야합니다.

for(int col=0; col<puzzle.length; col++) 
{ 
    match += puzzle[col][row]; 
} 
System.out.println(match); 

현재의 경기는

a 
av 
avx 
avxc 

입니다하지만 당신은 한 줄에 모두 인쇄하기 때문에 당신은 당신이 제대로 요구하는지 이해 한 경우

aavavxavxc 
0

는이를 평가 해보십시오.

char[][] puzzle = { 
         {'a', 'c', 'h' ,'t'}, 
         {'v', 'a', 'x', 'r'}, 
         {'x', 'r', 'e', 'i'}, 
         {'c', 'q', 'i', 'p'} 
         }; 

    String output = ""; 
    //we need to go throug the entire set of rows, but the tricky bit is in getting just say the first set of values [1][1], [2][1]... 
    //rather than getting the exterior as you were previously. 

    //Start by selecting element 1, 2, 3 from the outer array 
    for(int i = 0; i < puzzle.length; i ++) { 

     //Then perform the inner loop 
     for(int j = 0; j < puzzle[i].length; j++) { 
      output = output + puzzle[j][i]; //Here being the trick, select the inner loop first (j) and the inner second. Thus working your way through 'columns' 
     } 

     output = output +"\n"; 
    } 

    System.out.println(output); 

} 
0

당신은 당신의 배열 당신은 당신의 정규 표현식에 약간의 추가를 만들 즐길 수 puzzle[][]

 char[][] puzzle = {{'a', 'c', 'h' ,'t'}, 
      {'v', 'a', 'x', 'r'}, 
      {'x', 'r', 'e', 'i'}, 
      {'c', 'q', 'i', 'p'} 
      }; 

    // regex array 
    String[] regexs = new String[puzzle.length]; 

    int counter = 0; 
    for(int row=0; row<puzzle.length; row++) { 
     String match = "["; 

     for (int col = 0; col < puzzle.length; col++) { 
      match += puzzle[col][row]; 
      match += ","; 
     } 

     // Add regular expression into array 
     regexs[counter] = match + "]"; 

     counter++; 
    } 

    // Prepare 
    Pattern p = null; 
    Matcher m = null; 

    // Now parse with your inputs 
    for(String arg : args) { 

     for(String regex : regexs) { 
      p = Pattern.compile(regex); 
      m = p.matcher(arg); 

      if(m.find()) { 
       System.out.println(">>> OK. input: "+arg+" and matcher:"+regex); 
      } else { 
       // other output 
      } 
     } 
    } 

에 따라 정규 표현식을 사용할 수 있습니다.