【发布时间】:2020-10-25 21:32:57
【问题描述】:
我有一个关于排序的任务,要求我通过将以相同字母开头的字母放在一个组/区域中并按字母顺序对该组进行排序来对随机单词列表进行排序。我的代码对单词进行了排序,但我的问题是某些单词已经改变。例如,而不是将输出作为
- 一个安吉拉
- APPLE
- 一个苹果
- 一个苹果
- B阿布恩
- B全部
- C在
- c在
- P墨水
- P墨水
- S特夫
我会得到一个输出:
- 苹果
- 苹果
- 苹果
- 苹果
- 球
- 球
- 猫
- 猫
- 粉红色
- 粉色
- 史蒂夫
如您所见,一些单词已被更改,在某些情况下,大写字母的单词变成了小写字母,例如“cat”,我似乎无法找到我的错误所在。
这是我的排序代码;我的驱动程序类只接受随机单词列表:
import java.util.ArrayList;
import java.util.Collections;
public class ZoneSort
{
ArrayList[] arrayOfZones;
ArrayList<String> words;
public ZoneSort(ArrayList<String> words)
{
arrayOfZones = new ArrayList [ 26 ];
for(int index = 0; index < 26;index++)
arrayOfZones [ index ] = new ArrayList();
this.words = words;
putWordsIntoZones();
}
private void putWordsIntoZones()
{
for(String word: words)
{
int index = Character.toLowerCase(word.charAt(0)) - 97;
ArrayList<String> zoneAtIndex = arrayOfZones[index];
zoneAtIndex.add(word);
}
}
public void sortTheArrayOfZones()
{
for(ArrayList<String> zone : arrayOfZones )
{
sortZone(zone);
}
}
private void sortZone(ArrayList<String> zone)
{
for(int i = 1; i < zone.size(); i++)
{
String key = zone.get(i);
int j = i-1;
while(j>=0 && key.compareTo(zone.get(j)) > 0)
{
String x = zone.get(j+1);
zone.set(j, x);
j--;
}
String x = zone.get(j+1);
x = key;
}
}
public void printArrayOfZones()
{
System.out.println("The sorted words are");
for(ArrayList<String> zone:arrayOfZones)
{
for(String word: zone)
{
System.out.println(word);
}
}
}
【问题讨论】:
-
您能解释一下您的 sortZone 方法应该做什么吗?看起来不太对劲。
-
清楚你想要什么?将字符串大写更改为小写的逻辑是什么?
标签: java arrays sorting arraylist insertion-sort