WAP接受一个字符串,并且只打印出现次数相同且具有连续字母的单词



我正在解决这个问题(标题),我找不到错误,所以请帮助

输入:水牛被困在潮湿的田野里,道路被水淹没无处不在。

输出:buffalo, soggy, flooding

有3个单词的字母是连续的

package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
s = " ";
}
}
}
}
System.out.println("There are " + count + " consecutive words");
}
}

Enter the sentence
I love apples
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at com.company.Main.main(Main.java:18)
Process finished with exit code 1

我试着解决它,但它变得如此复杂

此处:

for (int j = 0; j < s.length(); j++){
if (s.charAt(j) == s.charAt(j + 1)){
System.out.println(s);
count++;
s = " ";
}
}

你正在遍历一个字符串,比较j索引字符和j+1索引字符。当j是最后一个字符的索引时,j+1将超出范围。如果您想以这种方式进行比较,您只需要转到倒数第二个索引(将倒数第二个索引与最后一个索引进行比较)。

这样代码就可以工作了:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;

for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length()-1; j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
}
}
s = " ";
}
}
System.out.println("There are " + count + " consecutive words");
}

你可以看到我已经移动了s = ";在for和if块之外的一段代码,将其留在else块中。如果不这样做,字符串变量s将不会在每个单词之后被清理。

最新更新