4

我有一个 java 类,它涉及一个字符串数组和两个 for 循环

用于遍历数组元素并打印它们以及它们在

数组,因为它们是 Strings 。

我希望有人帮我打印每个元素(字符串)一次,即使它

在数组中重复。

以下代码多次打印数组中的某个元素。

所以需要数组元素之间的比较

 public class myClassName {

 static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};

      public static String [] getArray()

      {

      String str[] = new String[myArray.length];

     for(int i=0;i<myArray.length;i++)

       {

       str[i] = myArray[i].toString();

        }

       return str;

     }

     public static void main( String [] args)

     {

     String d [] = getArray();

     int noOftimesRepeated;

          for(int i=0;i<getArray().length;i++)

          {

          noOftimesRepeated=1;

          String currentName = d[i];

          for(int j=0;j<getArray().length;j++)

          {

          if(i!=j && d[i].equalsIgnoreCase(d[j]))

          {

          noOftimesRepeated = noOftimesRepeated+1;

          }


          }

          int j =0;


          System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);

  }

 }

}

请问有没有不使用 .util.* 包的解决方案

我有第二次试验,但它打印出一个元素并且它是冗余的

只要。

 public class Javafool {

      static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama"};

     static String str2[] = new String[myArray.length];


     public static String [] getArray()
      {

      String str[] = new String[myArray.length];


      for(int i=0;i<myArray.length;i++)

      {

      str[i] = myArray[i].toString();

      }

      return str;

      }

      public static void main(String[] args) {

      String d [] = getArray();

      int noOftimesRepeated;

       sort(myArray);

       int no_of_repeat=1;

        String temp =null;

     int i   ;

      for(  i = 0;i<myArray.length-1;i++)

       {

           temp = myArray[i];

         myArray[i] = myArray[i+1];

         myArray[i+1] = temp;

       if(myArray[i].equals(temp))

       {

       no_of_repeat=  ++no_of_repeat;

       }

     }

      System.out.println(myArray[i]+""+temp+"\t"+"\t\t"+no_of_repeat);

      }

     public static void sort(String [] array) {

       String temp = null;

       for(int j=0;j<array.length;j++)
             {

         for(int i = 0; i<array.length-1;i++)
              {
           if(array[i].compareTo(array[i+1])<0)
                {

         temp = array[i];

         array[i] = array[i+1];

         array[i+1] = temp;

           }

           }}}}
4

12 回答 12

3

将字符串添加到Set<String>,从而消除重复值,然后打印它们:

List<String> list = Arrays.asList("Khaled", "Valderama",...);
Set<String> set = new LinkedHashSet<String>(list);

for(String s : set)
  System.out.println(s);
于 2013-09-09T12:06:28.790 回答
2

使用Map<String, Integer>, String 为输入字符串, Integer 为noOftimesRepeated计数器。

例子:

Map<String , Integer> map = new HashMap<String , Integer>(); 

// Add and count str Repeated times.
map.put(str, map.get(str) + 1);

// output string and counter pair in map
System.out.println(map);
于 2013-09-09T12:08:28.997 回答
1

如果您绝对不想使用java.util,您仍然可以手动排序并删除相邻的重复项:

public static void main(String[] args) {
  String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
  sort(myArray);

  String last=null;
  for(int i = 0;i<myArray.length;i++) {
    if(last==null || !myArray[i].equals(last)) {
      last = myArray[i];
      System.out.print(last+", ");
    }
  }
}

/*
 * Very naive method to sort elements. You can improve this with a merge sort.
 * Arrays.sort() would do the same job in a better way.
 */
public static void sort(String [] array) {
  String temp = null;

  for(int j=0;j<array.length;j++) {
    for(int i = 0; i<array.length-1;i++) {
      if(array[i].compareTo(array[i+1])<0) {
        temp = array[i];
        array[i] = array[i+1];
        array[i+1] = temp;
      }
    }
  }
}
于 2013-09-09T12:38:18.857 回答
0

你不需要 2 个 for 循环来做到这一点。只需这 3 行代码就可以了!:D

final List<String> lst = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");
    final Set<String> set = new HashSet<String>(lst);
    System.out.printf("Unique values: ", set);

如果没有 *ulit 包

您将需要一个自定义排序方法。伪代码可以这样(不是一种有效的方法)

"Given" lst array; 
Array temp = new Araay(lst.lenght); 

//two for loop for 
(int i = 0; i< lst.lenght; i++) { 
if(i==0){ 
temp[i] = lst[i]; // first array 
} 
for (int u = 0 ; u < lst.lenght; u ++){ 
//Write a code here if the lst[i] string is not equal to any temp[u] string, add then inside. Else dun care :) Cheers! 
} 
}
于 2013-09-09T12:15:56.667 回答
0

除了使用Set之外,您还可以创建唯一项目列表。

String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
List<String> myPrintList = new ArrayList<String>();        

for(String str : myArray){            
    if(!myPrintList.contains(str)){ // Check first if myPrintList contains the item already
        myPrintList.add(str); // Add if the list doesn't contain that item
    }
}

// Print list
for(String str : myPrintList){
    System.out.println(str);
}

根据评论编辑:

不知道为什么你不想使用 util 包,但是 -

String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
StringBuilder uniqueNames = new StringBuilder(); // For storing all unique names separated by a pipe (|)        

for(String str : myArray){

    if(uniqueNames.indexOf(str) < 0){ // Check if str exists in builder yet
        uniqueNames.append(str); // Add str if it doesn't exist
        uniqueNames.append("|"); // Add delimiter                
    }

}

String[] myPrintArray = uniqueNames.toString().split("\\|"); // Get an array by splitting using the pipe delimiter

for(String str : myPrintArray){        
    System.out.println(str);
}
于 2013-09-09T12:14:10.980 回答
0

您可以执行以下操作,

String[] myArray = { "Khaled", "Valderama", "Daoud", "Khaled",
        "Rasheed", "Daoud", "Valderama", "Khaled" };
Set<String> sets = new HashSet<String>(Arrays.asList(myArray));
System.out.println(Arrays.toString(sets.toArray()));
于 2013-09-09T12:11:47.853 回答
0

您可以使用set. Set将避免添加重复项。

    String [] myArray = {"Khaled","Valderama","Daoud",
                        "Khaled","Rasheed","Daoud","Valderama","Khaled"};
    Set<String> set=new HashSet<>();
    for(String i:myArray){
        set.add(i);
    }
    System.out.println(set);

如果您不想使用java.util.*包,请尝试以下方式。

  String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud",
                       "Valderama","Khaled"};
    String[] newArr=new String[myArray.length];
    int j=0;
    for(String i:myArray){
        if(!Arrays.toString(newArr).contains(i)){
            newArr[j]=i;
            j++;
        }
    }
于 2013-09-09T12:12:09.607 回答
0

尝试这个。对于重复项,for 循环不会完全运行

import java.util.ArrayList;
public class myClassName {

 static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
      public static String [] getArray()
      {
          String str[] = new String[myArray.length];
          for(int i=0;i<myArray.length;i++)
          {
              str[i] = myArray[i].toString();
          }
       return str;
     }

     public static void main( String [] args)
     {
         String d [] = getArray();
         int noOftimesRepeated;
         ArrayList<String> list = new ArrayList<String>();
          for(int i=0;i<getArray().length;i++)
          {
              if(list.contains(d[i]))
                    continue;
              noOftimesRepeated=1;

              for(int j=0;j<getArray().length;j++)
              {
                  if(i!=j && d[i].equalsIgnoreCase(d[j])  )
                  {
                      noOftimesRepeated = noOftimesRepeated+1;
                      list.add(d[i]);
                  }
              }
              System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);

          }
     }
}
于 2013-09-09T12:18:03.577 回答
0

我找到了解决方案,(以下解决方案不涉及java.util

package ,它依赖于快速排序算法)。

谢谢你们。

     public class Javafool 

     {

static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama","Daoud"};

static String str2[] = new String[myArray.length];

     public static void main(String[] args)

     {

     int [] noOftimesRepeated;

      sort(myArray);

      int no_of_repeat=1;

      String temp =null;

       int i   ;

       int count = 0;

       String previous = null;

      for (String s : myArray) 

      {

     if (s.equals(previous))

     {

     count++;
     } 

     else 

     {

     if( previous !=null)

     System.out.println(previous + " :" + count);

     previous = s;

     count = 1;

     }

     }

     if (myArray.length > 0)

    {

    System.out.println(previous + " :" + count);

    }

    }

   public static void sort(String [] array) {

   String temp = null;

   for(int j=0;j<array.length;j++)

  {

 for(int i = 0; i<array.length-1;i++)

  {

  if(array[i].compareTo(array[i+1])<0)

  {

  temp = array[i];

  array[i] = array[i+1];

  array[i+1] = temp;

 }

 }

    } } }
于 2013-09-11T13:19:40.327 回答
0
public static void main(String[] args) {
    List<String> myArray = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");

    Set<String> sets = new HashSet<String>();

    sets.addAll(myArray);

    System.out.println(sets);
}

输出: [Khaled, Valderama, Rasheed, Daoud]

于 2013-09-09T12:10:00.917 回答
0

我同意前一个人的观点,首先你应该将你的arraylist按顺序排列,你可以尝试快速排序算法,其次你应该将当前元素与前一个元素进行比较,如果它们相等,则不要打印它。这很容易,对吧?

您可以将快速排序算法函数提取到 util 类中,以便在以后的开发中使用它。

于 2013-09-09T12:46:56.670 回答
0

问题是数组在内存中是固定大小的,您不能从数组中删除重复的值。

因此,要么将重复值转移到不需要的值(如零或任何字符串),要么使用ArrayList,它允许您从列表中删除值(因为列表不是固定大小,您可以更改它)。

于 2019-03-08T00:17:58.450 回答