我正在尝试重新排列任何给定字符串中的单词(20 个单词或更少)。我遇到这个问题是因为我无法打印字符串中的最后一个单词。我尝试修改循环范围,但无法解决问题。
public class ListString {
String[] list = new String[20];
int n = 0;
public void read(){
Scanner in = new Scanner(System.in);
System.out.println("Please enter the sentence");
String s = in.nextLine();
String temp = "";
for (int i=0; i<s.length(); i++)
{
char ch = s.charAt(i);
if ((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')) // range from a to z
temp = temp + ch;
else
{
if (temp.length() > 0)
{
list[n] = temp;
n++;
temp = "";
}
}
}
}
public void print(){
System.out.print(list[0]);
for(int i=0;i<n;i++)
System.out.print(" "+list[i]);
System.out.println(" ");
}
public void sort(){
for (int i = 0; i < n; i++) {
String key = list[i];
int j = i - 1;
while (j >= 0 && (list[j].compareToIgnoreCase(key)>0)) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = key;
}
}
}
当您点击字符串的末尾并且 temp 不为空时,就会发生这种情况。要修复它,您可以在循环后添加相同的 if 语句:
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
temp = temp + ch;
} else {
if(temp.length() > 0) {
list[n] = temp;
n++;
temp = "";
}
}
}
if(temp.length() > 0) {
list[n] = temp;
n++;
temp = "";
}
此外,您还需要修复输出以不打印第一个单词两次:
public void print() {
for(int i = 0; i < n; i++) {
System.out.print(list[i] + " ");
}
System.out.println();
}
修复前输出:
a b c d e f g h i j k l m n o p q r s t
a a b c d e f g h i j k l m n o p q r s
修复后输出:
a b c d e f g h i j k l m n o p q r s t
a b c d e f g h i j k l m n o p q r s t
更新:
您也可以使用流在一行中解决您的问题
public void read() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the sentence");
String s = in.nextLine();
list = Arrays.stream(s.split(" ")).limit(20).sorted().toArray(String[]::new);
}
它按空格字符拆分输入字符串,取前 20 个单词,对它们进行排序并创建它们的数组。
输出:
t s r q p o n m l k j i h g f e d c b a z z z z z
a b c d e f g h i j k l m n o p q r s t
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句