我试图将第一个单词移到Java中的最后一个位置。但我的节目没有打印句子。我能错过什么?
这是我的计划:
import java.util.Scanner;
public class FirstLast {
public static void main(String[] args) {
System.out.println("Enter line of text.");
Scanner kb = new Scanner(System.in);
String s = kb.next();
int last = s.indexOf("");
System.out.println(s);
s = s.sub string(0, last) ";
System.out.println("I have rephrased that line to read:");
System.out.println(s);
}
}
答案 0 :(得分:1)
int last = s.indexOf(""); // Empty string, found at 0
应该是
int last = s.lastIndexOf(' '); // Char possible too
答案 1 :(得分:0)
假设您的输入是以空格分隔的字符串,那么您可以像这样交换第一个和最后一个位置。
String[] words = s.split(" ");
String tmp = words[0]; // grab the first
words[0] = words[words.length]; //replace the first with the last
words[words.length] = tmp; // replace the last with the first
答案 2 :(得分:0)
请阅读扫描仪API文档:
扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。
也就是说,你只能使用kb.next()获得第一个单词。要修复它,你应该在while循环中获取所有单词或使用以结尾分隔符的行。
答案 3 :(得分:0)
您可以尝试这样的事情:
public static void main(String[] args) {
System.out.println("Enter line of text.");
Scanner kb = new Scanner(System.in);
String s = kb.nextLine(); // Read the whole line instead of word by word
String[] words = s.split("\\s+"); // Split on any whitespace
if (words.length > 1) {
// v remove the first word and following whitespaces
s = s.substring(s.indexOf(words[1], words[0].length())) + " " + words[0].toLowerCase();
// ^ Add the first word to the end
s = s.substring(0, 1).toUpperCase() + s.substring(1);
}
System.out.println("I have rephrased that line to read:");
System.out.println(s);
}
如果你不关心保留空格,你可以更简单地进行吐痰
输出:
Enter line of text.
A aa aaa aaaa
I have rephrased that line to read:
Aa aaa aaaa a
有关详细信息,请参阅http://docs.oracle.com/javase/tutorial/java/data/strings.html和http://docs.oracle.com/javase/7/docs/api/java/lang/String.html