我有一个 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;
}
}}}}