【发布时间】:2016-12-03 07:15:59
【问题描述】:
所以,我昨天发布了这个几乎相同的代码,询问如何在使用 .split 后将标点符号留在倒置句子的末尾。我仍在为此苦苦挣扎,但我也遇到了相同代码的另一个问题:这是我的屏幕截图http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
正如你们可能从屏幕截图中看到的那样,当提示用户添加另一个句子时,前一个句子会被再次读回。
我的问题是:
- 如何使用
charAt识别未定义索引处的字符(用户输入的长度不同) - 如何在用户决定继续阅读后停止我的句子。
再一次,正如我所说,我昨天发布了这段代码,但线程死了,我还有其他问题在原帖中没有提到。
【问题讨论】:
-
我尝试在输出中添加屏幕截图。链接在这里。 [1]:i.stack.imgur.com/peiEA.png
-
如果你在每个循环结束时都执行
String sentence = null;和String[ ] words = null;以便它可以被垃圾回收呢? -
您能否澄清您在第 1 部分中的意思?具体来说,“未定义的索引”是什么意思
-
我正在尝试做的部分事情是反转一句话:你好,我的名字是鲍勃!应该变成 Bob 是我的名字 你好!因此,整个句子颠倒过来,但标点符号保留在末尾。有人建议我使用 charAt() 来查找句子中的最后一个字符,然后将其放在末尾。我不知道如何将 charAt() 用于我不知道最后一个索引在哪里的字符串,因为它是确定长度的用户。