【发布时间】:2020-12-29 04:00:37
【问题描述】:
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 初学者。
【问题讨论】:
-
实际输出看起来非常像您的预期输出。也许您想明确说明您得到的输出存在什么问题。
-
我必须在我的一个实际运行示例中修复格式。最后一行有“好”。实际上在控制台输出中它前面有一个空格。第二个例子是它如何运行一些字符的印章。
-
或者将其包裹在
<pre></pre>标签中以避免代码块的颜色。见stackoverflow.com/editing-help -
@Leonartist 显然这是您需要在问题中包含的信息。
-
@Leonartist 你可以使用
int space2 = sentence.indexOf(" ");和int space3 = sentence2.indexOf(" ");。如果您打算将space2和space3分别保存第一个空格出现在sentence2和sentence3中的索引,那就错了。
标签: java string substring indexof sentence