我之前用一个更基本的以下代码版本编写了一篇文章。使用数组列表按升序和降序排列字符串
我重新安排了它,但它仍然不起作用。每当我输入一个新的字符串,它不会进入两个列表中的任何一个。它给了我这样的:
这是你的升序排列的字符串:[]
这是你的降序排列的字符串:[]
公共类Stringseries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Start the sequence by inputting a string DIFFERENT than 'quit'. When you DO want to end it, input 'quit'");
String encore = scanner.nextLine();
List<String> ascending = new ArrayList<>();
List<String> descending = new ArrayList<>();
int loop = 0;
String longest = "";
String lastInput = "";
boolean inserted = false;
while (!encore.equalsIgnoreCase("quit")) {
loop = ++loop;
encore = encore.replaceAll("\\s+",""); // this way, the length of the strings is only defined by the characters in the string, and not characters + whitespaces.
for(int i = 0; i < ascending.size(); i++) {
if(ascending.get(i).length() > encore.length()) {
ascending.add(i, encore);
inserted = true;
} if(!inserted) {
ascending.add(encore); }
} for(int i = 0; i > descending.size(); i++) {
if(descending.get(i).length() < encore.length()) {
descending.add(i, encore);
inserted = true;
} if(!inserted) {
descending.add(0, encore); }
}
if (longest.length() < encore.length()) {
longest = encore; }
System.out.println("Enter the string you want to put in your sequence of strings");
encore = scanner.nextLine();
}
if (descending != null) { // we check to see if the "descending" string is empty (we could do this with "ascending" mind you).
System.out.println("Here are your strings in ascending order : " + ascending);
System.out.println("Here are your strings in descending order : " + descending);
System.out.println("Here is the longest string : " + longest);
} else if (descending == null) {
System.out.println("You have not entered any strings, therefore the program doesn't display any string :("); // customised message.
}
}
}
你不需要空当你用'new ArrayList'初始化时检查'降序' –
你怎么样不保存'降序',只是简单地按相反的顺序打印出集合? – cypher