【发布时间】:2014-08-27 20:03:35
【问题描述】:
我有一个项目,其中程序询问用户它应该运行多少次。在每次运行期间,都会创建一个列表并添加元素。数组中的这些元素不是按字母顺序排序的,而是按以下顺序排序的:
q,w,e,r,t,y,u,i,o,p,l,k,j,h,g,f,d,s,a,z,x,c,v,b,n,m
我能够运行我的程序直到它接受输入,但我不知道下一步该做什么......
示例输入
2
3
what
are
you
2
sad
set
样本输出
what
you
are
set
sad
这是我的代码:
import java.util.*;
public class WeirdWritings {
public static void main(String[] args) {
int data,word,ctr,i,ii;
char[] rLetter = {'Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'};
String entry;
Scanner s = new Scanner(System.in);
data=s.nextInt();
for (ctr=0;ctr<rLetter.length;ctr++)
System.out.print(rLetter[ctr]);
System.out.println();
for (ii = 0; ii<data; ii++) {
word=s.nextInt();
List<String> array_ii = new ArrayList<String>();
for(i=0; i<word; i++) {
entry=s.next();
array_ii.add(entry);
}
}
}
}
将比较器添加到它以完成它
公共类 MyComparator 实现 Comparator {
private int[] charRank;
public MyComparator() {
char[] charOrder = {'Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'};
this.charRank = new int[26];
for(int i=0; i<25; i++) {
this.charRank[charToInt(charOrder[i])] = i;
}
}
public int compare(String s1, String s2) {
// returns
// Positive integer if s1 greater than s2
// 0 if s1 = s2
// Negative integer if s1 smaller than s2
s1 = s1.toUpperCase();
s2 = s2.toUpperCase();
int l = Math.min(s1.length(), s2.length());
int charComp;
for(int i=0; i<l; i++) {
charComp = this.charRank[charToInt(s1.charAt(i))] - charRank[charToInt(s2.charAt(i))];
if(charComp != 0)
return charComp;
}
return s1.length() - s2.length();
}
//works for c between 'A' and 'Z' - upper case letters
private static int charToInt(char c) {
return c - 65;
}
//works for 0<=i<=25
private static char intToChar(int i) {
return (char) (i + 65);
}
public static void main(String[] args) {
int data,word,ctr,i,ii;
char[] rLetter = {'Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'};
String entry;
Scanner s = new Scanner(System.in);
data=s.nextInt();
for (ctr=0;ctr<rLetter.length;ctr++)
System.out.print(rLetter[ctr]);
System.out.println();
for (ii = 0; ii<data; ii++) {
word=s.nextInt();
String[] array_ii = new String[word];
for(i=0; i<word; i++) {
entry=s.next();
array_ii[i]=(entry);
}
Arrays.sort(array_ii, new MyComparator());
for(i=0; i<word; i++) {
System.out.println(array_ii[i]);
}
}
}
}
【问题讨论】:
-
我没有看到对您的代码进行排序的任何尝试;我怀疑你应该写一个遵循你发布的“qwerty”排序规则的
Comparator。
标签: java sorting comparator