如何解决Java句子缩短程序无法正常工作
import java.util.Scanner;
public class SentenceShortener {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String sentence = "";
String sentence2 = "";
String sentence3 = "";
String finalcount = "";
System.out.println("Input sentence ");
sentence = kbd.nextLine();
int space = sentence.indexOf(" ");
System.out.println(sentence.substring(space+1));
sentence2 = sentence.substring(space+1);
int space2 = sentence.indexOf(" ");
System.out.println(sentence2.substring(space2+1));
sentence3 = sentence2.substring(space2+1);
int space3 = sentence2.indexOf(" ");
System.out.println(sentence3.substring(space3+1));
finalcount = sentence3.substring(space3+1);
System.out.println("Your " + sentence.length() + " character long sentence was shortened to " + finalcount.length() + " characters.");
}
}
我创建了一个程序,该程序应该缩短四个单词的句子,然后缩短到更长的“句子”,并计算出您将句子缩短为多少个字符。
这是它的工作方式:
Input sentence
The car runs good.
car runs good.
runs good.
good.
Your 18 character long sentence was shortened to 6 characters.
它的实际运行方式:
Input sentence
The car runs good.
car runs good.
runs good.
good.
Your 18 character long sentence was shortened to 6 characters.
另一次运行:
Input sentence
Why is it raining?
is it raining?
t raining?
aining?
Your 18 character long sentence was shortened to 7 characters.
我是Java的初学者。
解决方法
确定空间索引的逻辑不正确。 尝试将代码修改为具有
int space2 = sentence2.indexOf(" ");
int space3 = sentence3.indexOf(" ");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。