2013-03-04 33 views
-3

我正在尝试将第一个单词移至Java中的最后一个位置。但是我的程序没有打印这个句子。我可能会错过什么?将第一个单词移至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); 
    } 
} 
+1

首先,它不会编译...'s.sub string'不是有效的Java语法。 – Makoto 2013-03-04 07:09:14

+0

使用int last = s.lastIndexOf(''); – 2013-03-04 07:15:02

回答

1
int last = s.indexOf(""); // Empty string, found at 0 

应该

int last = s.lastIndexOf(' '); // Char possible too 
+0

我得到了答案,但仍然有负面影响。这不是问题吗? – user2130758 2013-03-11 00:58:56

+0

请不要采取这样的个人,这种小型雪崩发生:从不可编辑的,到标记的问题,拒绝。这是一个不完善的过滤机制来处理大量的问题。恕我直言,你确实有一个有效的问题。 – 2013-03-11 09:19:01

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 
0

请阅读扫描仪API文件:

扫描器断开其输入到使用定界符模式,默认情况下与空白匹配。

也就是说,您只能使用kb.next()获取第一个单词。为了解决这个问题,你应该在while循环中获得所有的单词,或者以行结尾作为分隔符。

Scanner API

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.htmlhttp://docs.oracle.com/javase/7/docs/api/java/lang/String.html

+0

让我试试这些。谢谢你太多了!我对编程毫无头绪。刚开始。昨晚完全强调了我。 – user2130758 2013-03-04 18:00:02

+0

你真棒!有效!谢谢!!输出是:输入文本行。没有标点符号 Java是语言 我已将该行改为: 是Java语言 – user2130758 2013-03-05 03:00:22

+0

如何获得最终输出以将第一个字母显示为大写? – user2130758 2013-03-05 03:15:53

相关问题