对于这个程序,我需要有用户输入字符串,然后将它们与反向的对应字符串放在一个数组中。整个阵列将被按字母顺序排列。因此,它应该像这样工作:Alphabetizing字符串和颠倒的字符串?
输入:草莓香蕉,苹果,葡萄
输出:苹果,ananab,香蕉,elppa,葡萄,separg,草莓,yrrebwarts
我有这个代码,它在一定程度上有效。但是,它只是将反转和正常但分开的按字母顺序排列。因此,它结束了看起来像这样:
- 输出:ananab,elppa,separg,yrrebwarts,苹果,香蕉,葡萄,草莓
正如你可以看到它是字母排序的话有些学位,但不是它应该如何。这里是我的代码:
import java.util.Scanner;
public class WordGame {
public static void main(String[] args) {
String reverseInput = " "; //creates an empty string where the reverse will be stored before putting it into the array
String[] wordArray = new String[1000]; //creates an array that allows for 500 words, and 500 reverses of said words
int s = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the words you would like to reverse. To finish entering words enter a blank line:");
String userInput = sc.nextLine(); //allows for user to input words
int length = userInput.length();
int i = 0;
while (!userInput.equals("")){ //runs until the user enters a blank line
reverseInput = " ";
for(i = length - 1; i >= 0; i--)
reverseInput += userInput.charAt(i);
wordArray[s] = userInput; //reverses user inputted strings by taking the last letter and putting it in front, repeating until the whole word is reversed
wordArray[s + 1] = reverseInput;
s += 2;
userInput = sc.nextLine();
length = userInput.length();
}
for(int j = 0; j < s-1; j++){ //beginning of alphabetical sorting
for(int k = 0; k < s-1-j; k++){
int l = 0;
while((int)wordArray[k].charAt(l) == (int)wordArray[k+1].charAt(l))
l++;
if ((int)wordArray[k].charAt(l) > (int)wordArray[k+1].charAt(l)){
String holder = wordArray[k];
wordArray[k] = wordArray[k+1];
wordArray[k+1] = holder;
}
}
}
for(i = 0; i < wordArray.length; i++){
if (wordArray[i]!= null){
System.out.print(wordArray[i] + " "); //prints out contents of array
}
}
}
}
我不确定是什么问题。任何帮助将非常感激。谢谢!
对您可以使用什么有任何限制吗?即没有列表或您不被允许使用内置的排序功能? – vandale 2014-12-08 00:06:21
@vandale我们不能使用内置的排序函数或列表。我在这里使用的一切都是我们可以使用的程度。 – throwaway298 2014-12-08 00:09:55