2017-02-22 4 views
-1

String을 통해 정렬하고 중복을 제거 할 수있는 프로그램을 개발하려고합니다. 이 중첩 된 루프를 사용하고 있습니다. 그러나 내 코드를 실행하면 몇 단어를 반복해서 반복합니다.중첩 된 루프로 중복 제거 java

[ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask] 
[not, null, not, null, not, null, not, null, not, null, not, null, not, null, not, null, not] 
[what, null, what, null, what, null, what, null, what, null, what, null, what, null, what, null, what] 
[your, null, your, null, your, null, your, null, your, null, your, null, your, null, your, null, your] 
[country, null, country, null, country, null, country, null, country, null, country, null, country, null, country, null, country] 
[can, null, can, null, can, null, can, null, can, null, can, null, can, null, can, null, can] 
[do, null, do, null, do, null, do, null, do, null, do, null, do, null, do, null, do] 
[for, null, for, null, for, null, for, null, for, null, for, null, for, null, for, null, for] 
[you, null, you, null, you, null, you, null, you, null, you, null, you, null, you, null, you] 
[ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask] 
[what, null, what, null, what, null, what, null, what, null, what, null, what, null, what, null, what] 
[you, null, you, null, you, null, you, null, you, null, you, null, you, null, you, null, you] 
[can, null, can, null, can, null, can, null, can, null, can, null, can, null, can, null, can] 
[do, null, do, null, do, null, do, null, do, null, do, null, do, null, do, null, do] 
[for, null, for, null, for, null, for, null, for, null, for, null, for, null, for, null, for] 
[your, null, your, null, your, null, your, null, your, null, your, null, your, null, your, null, your] 
[country, null, country, null, country, null, country, null, country, null, country, null, country, null, country, null, country] 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 17 

나는 이것에 대한 넷빈즈를 사용하고 있습니다 :

package q2; 

import java.util.Arrays; 

public class Q2 { 

public static void main(String[] args) { 
    String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"; 
    String lowercaseSentence; 
    lowercaseSentence = sentence.toLowerCase(); 
    String[] sentenceWords = lowercaseSentence.split(" "); 
    int LenghtofSentence = sentenceWords.length; 
    String[] unique = new String[LenghtofSentence]; 

    for (int i = 0; i <= LenghtofSentence; i++) { 
     //System.out.println(i); 
     for (int j = 0; j <= LenghtofSentence; j++) { 
      if (!sentenceWords[i].equals(unique)) { 
       unique[j] = sentenceWords[i]; 
       j++; 
      } else { 
       j++; 
      } 
     } 
    System.out.println(Arrays.toString(unique)); 
    } 
} 
} 

내가 무엇입니까 오류 메시지입니다. 어떤 도움을 주셔서 감사합니다. 감사합니다. Keir

+1

코드를 디버그하십시오. – f1sh

+1

'Set'(예 :'LinkedHashSet')을 사용하지 않는 이유는 무엇입니까? – Thomas

+5

'for' 루프를 쓸 때'for (int i = 0; i <= LenghtofSentence; i ++)'배열의 끝을지나 가게됩니다. '<='대신에'<'이어야합니다. – khelwood

답변

-1
package test; 


import java.util.ArrayList; 

import java.util.Arrays; 


public class Test { 


     public static void main(String[] args) { 

      String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"; 

      String lowercaseSentence; 

      lowercaseSentence = sentence.toLowerCase(); 

      String[] sentenceWords = lowercaseSentence.split(" "); 

      int LenghtofSentence = sentenceWords.length; 

      String[] uniqueString = new String[LenghtofSentence]; 

      ArrayList<String> unique = new ArrayList<String>(); 

      int k=0; 
      for(int i=0;i<LenghtofSentence;i++) 
      { 
      if(!unique.contains(sentenceWords[i])) 
      { 
       unique.add(sentenceWords[i]); 
       k++; 
      } 
      } 
      for(int i=0;i<unique.size();i++) 
      { 
       uniqueString[i] = unique.get(i); 
       System.out.print(" "+uniqueString[i]); 
      } 
     } 
    } 
4

왜이 루프를 사용하여 복잡한 지 알 수 없습니다.

Java에서 Set을 사용하면 간단하게 수행 할 수 있습니다. Set은 중복 요소가없는 모음입니다. 더 link

Set<String> mySet = new LinkedHashSet<String>(Arrays.asList(sentenceWords)); 

를 들어이 자동으로 중복을 제거합니다.

String[] unique = myset.toArray(new String[myset.size()]); 

또한 위의 코드를 사용하기 전에 다음을 가져옵니다 : 다음과 같이 Set에서 중복없이 배열을 다시 얻을 수있는 단어가 배열에 존재하는 순서를 유지합니다 LinkedHashSet를 사용

import java.util.Arrays; 
import java.util.LinkedHashSet; 
import java.util.Set; 

. 희망이 도움이됩니다.

+1

단어 순서를 유지하기 위해'LinkedHashSet'을 사용하십시오. –

+0

예, 코드가 업데이트됩니다. – SachinSarawgi

0

귀하의 질문이 연습으로 보입니다. 해결책을 찾는 방법을 설명하는 제안은하지 말아야한다고 생각합니다. 첫째, 운동에서 Java 콜렉션을 사용할 수 있다면 Set<String>을 사용하면 단어가 복제되었는지 확인하고 중복되지 않은 세트를 제공하기 때문에 개선이 될 것입니다.

연습 중에 배열 만 사용할 수있는 경우 다른 해결책을 사용해야합니다. 먼저 unique 배열을 반복하여 중복이 있는지 확인한 다음 unique 배열을 정렬하는 것이 좋습니다.

한편 Netbeans을 사용하면 단계별로 코드를 실행할 수 있습니다 (@ f1sh 권장).

0

우선 논리가 완벽하지 않습니다.

ArrayIndexOutOfBound

배열의 길이 배열 & 인덱스의 요소의 개수가 말했듯 0

에서 시작하기 때문에 때문에 unique & sentenceWords는 루프 모두 <<= 대체 배열 잘못된 인덱싱 발생할 것이다 당신의 논리에 대해 생각하기 전에 그것은 완벽하지는 않습니다. 다음 트릭을 사용하여 목표를 달성 할 수 있습니다.

& 중복을 제거하는 코드에 다음 코드를 바꾸십시오. 배열을 정렬하십시오.이 문장 배열 unique의 실행 후

String[] unique = Arrays.stream(sentenceWords) 
    .distinct().sorted().toArray(String[]::new); 

어휘 순서로 정렬 형태로 배열 sentenceWords의 별개의 요소를 포함한다. 자세한 내용은 javadocs를 참조하십시오.