-3

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);
    }
}
4

4 に答える 4

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

する必要があります

    int last = s.lastIndexOf(' '); // Char possible too
于 2013-03-04T07:09:55.073 に答える
1

次のようなことを試すことができます:

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

于 2013-03-04T07:23:20.163 に答える
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
于 2013-03-04T07:11:18.003 に答える
0

Scanner API ドキュメントをお読みください:

Scanner は、デフォルトで空白に一致する区切り文字パターンを使用して、入力をトークンに分割します。

つまり、kb.next() を使用して最初の単語のみを取得します。これを修正するには、while ループですべての単語を取得するか、行末を区切り記号として使用する必要があります。

スキャナー API

于 2013-03-04T07:14:18.377 に答える