私はJavaが初めてで、問題に混乱しています。これが私がこれまでに思いついたものです。私はまだそれに取り組んでいます、何か進展があれば、ここに投稿します。
public class charArray {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
//output should be ["apple", "ball"]
checkDuplicate(strArray);
}
public static String[] checkDuplicate(String[] strArray){
String[] newArray = new String[]{};
for(int i = 0; i < strArray.length; i++){
for(int j = 0; j < i; j++){
if (strArray[i].equals(srtArray[j])){
newArray = strArray[i];
}
}
}
return newArray[];
}
}
新しい進歩: わかりました、私の平凡な頭はここまで来ました: (そして解決策は機能します) Duplicate 要素の一意の配列を出力します。しかし、メソッドを呼び出して、同じコードを実装する必要があります。どんな助けでも大歓迎です。
import java.util.*;
public class setChar {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
Set set = new HashSet();
Set uniqueSet = new HashSet();
for(int i = 0; i < strArray.length ; i++ ){
boolean b = set.add(strArray[i]);
if(b == false){
uniqueSet.add(strArray[i]);
}
}
Iterator it = uniqueSet.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
}
出力は次のとおりです 。
最後に、適切な戻り値の型を持つメソッドで実装されました。これをさらに最適化できる場合は、お知らせください。ご提案いただきありがとうございます。作業コードは次のとおりです。
public class retUnique {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
System.out.println(printUnique(strArray));
}
public static Set<String> printUnique(String[] strArray){
Set<String> set = new HashSet<String>();
Set<String> uniqueSet = new HashSet<String>();
for(int i = 0; i < strArray.length ; i++ ){
boolean b = set.add(strArray[i]);
if(b == false){
uniqueSet.add(strArray[i]);
}
}
return(uniqueSet);
}
}