gpt4 book ai didi

java - 按字母顺序排列字符串和反转字符串?

转载 作者:行者123 更新时间:2023-12-01 12:09:21 24 4
gpt4 key购买 nike

对于这个程序,我需要用户输入字符串,然后将其与相反的对应项一起放入数组中。然后整个数组将按字母顺序排列。所以它应该像这样工作:

  • 输入:草莓香蕉、苹果、葡萄

  • 输出:苹果、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
}
}
}
}

我不确定问题是什么。任何帮助将非常感激。谢谢!

最佳答案

据我所知,您在“reverseInput”前面添加了一个额外的空格 reverseInput = "";因为您的反向字符串不会以您认为的字符开头(它以空白开头),所以结果不是您真正想要的。尝试删除空白并重试您的代码。

关于java - 按字母顺序排列字符串和反转字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com