2014-10-20 2 views
-1

좋아요, 분명히 저는 Java에 익숙하지 않습니다. 현재 내가 원하는 것은 문자열을 문자 배열로 나누고 문자를 대체하여 문자열을 암호화하는 매우 간단한 프로그램입니다 새로운 것들과.Java for 루프에서 문자 교체

그래서 지금까지 분할 된 문자열을 비교하고있는 알파벳이 포함 된 키 배열을 만드는 것이 었습니다. 그리고 기본적으로 값 배열로 문자를 대체하려고합니다. 알파벳 만 뒤로.

내 코드는 지금까지 값을 인쇄 할 때 작동하지만 제대로 문자를 바꾸지는 못합니다.

public class Main { 

    public static void main(String[] args) { 

     char[] keyArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
     char[] valueArray = {'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'p', 'q', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'}; 

     String myString = "abcxyz"; 
     char[] myStringArray = myString.toCharArray(); 

     for(int x = 0; x<myString.length(); x++) 
     { 
      for(int i = 0; i<keyArray.length; i++) 
      { 
       if(myStringArray[x] == keyArray[i]) 
       { 
        //System.out.println(valueArray[i]); would give the output "zyxcba" as expected 
        myStringArray[x] = valueArray[i]; // this will only change the characters in the first half of keyArray 
       } 
      } 
     } 

     System.out.println(myStringArray); //Outputs "abccba" instead of "zyxcba" 
    } 
} 
+1

도움이 될 수 있습니다. http://stackoverflow.com/q/11588916/535275 –

답변

3

문제는 이미 교체 한 후에도 키 배열을 계속 반복한다는 것입니다. 두 번째 대체 할 수 있습니다.

교체를 완료하면 for 루프에서 '중단'해야합니다.

public class Main { 

    public static void main(String[] args) { 

     char[] keyArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
     char[] valueArray = {'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'p', 'q', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'}; 

     String myString = "abcxyz"; 
     char[] myStringArray = myString.toCharArray(); 

     for(int x = 0; x<myString.length(); x++) 
     { 
      for(int i = 0; i<keyArray.length; i++) 
      { 
       if(myStringArray[x] == keyArray[i]) 
       { 
        //System.out.println(valueArray[i]); would give the output "zyxcba" as expected 
        myStringArray[x] = valueArray[i]; // this will only change the characters in the first half of keyArray 
        break; //Exit the loop checking against the keyArray 
       } 
      } 
     } 

     System.out.println(myStringArray); //Outputs "abccba" instead of "zyxcba" 
    } 
} 
+0

아아, 이해합니다! 고맙습니다. 모든 것이 예상대로 작동합니다 :) – s1nclair

0

공용 클래스 홈페이지 {

public static void main(String[] args) { 

    char[] keyArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
    char[] valueArray = {'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'p', 'q', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'}; 

    String myString = "abcxyz"; 
    char[] myStringArray = myString.toCharArray(); 

    for(int x = 0; x<myString.length(); x++) 
    { 
     for(int i = 0; i<keyArray.length; i++) 
     { 
      if(myStringArray[x] == keyArray[i]) 
      { 
       //System.out.println(valueArray[i]); would give the output "zyxcba" as expected 
       myStringArray[x] = valueArray[i]; // this will only change the characters in the first half of keyArray 
       break; //Introduced break so that when the answer is set, break and move to the next iteration of myStringArray 
      } 
     } 
    } 


    System.out.println(myStringArray); //Outputs "abccba" instead of "zyxcba" 
} 

은}

나는 항목이 일치 할 때 제어하는 ​​사이에 휴식을 소개했다.

이 방법을 여러 가지 방법으로 최적화 할 수 있습니다. 하지만 중요한 것은 x * i 비교가 필요하지 않을 때 비교하지 말아야한다는 것입니다.

+0

문자열을 charAt 또는 substring 메서드를 사용하여 배열로 변환하는 대신 하나 이상의 작업을 추가합니다. – scorpionmance

+0

답변 해 주셔서 감사합니다. 그래, 아직 다양한 옵션을 탐색 해 보았습니다. 자바에서의 첫 번째 프로그램입니다. 확실히 문자열 작업을 살펴볼 것입니다! 하지만 x * i 비교가 무슨 뜻입니까? for-loops가 아닌 다른 것을 사용해야한다고 말하는거야? – s1nclair

+0

x * i에 의해,이 경우의 총 건수는 문제를 효율적으로 해결할 수없는 myString.length() * keyArray.length()입니다. 다음과 같은 경우에는 결과를 잘 얻고 있습니다. 내부 루프의 끝 부분. – scorpionmance