连接用户输入JAVA

时间:2014-10-14 19:45:43

标签: java string-concatenation

这是我到目前为止所拥有的。我希望程序打印出用户输入的单词作为句子。但 我不知道我到目前为止所编写的代码是如何实现的。 例如:如果你进入了 你好 世界 完成

该计划应该说:“Hello World”

import java.util.Scanner;

public class Chapter3ProblemsSet {

    public static void main(String [] args) {

    String word = "";
    final String SENTINEL = "done";
    double count = 0; 

    String userInput = "";

    Scanner in = new Scanner (System.in);


    System.out.println("Please enter words: ");
    System.out.println("Enter done to finish.");
    word = in.next();

    do {
        word = in.next();
        count++;   
        System.out.print(" "+word);
    }
    while (!word.equals(SENTINEL));


    System.out.println(" "+word);

    }
}

3 个答案:

答案 0 :(得分:2)

您需要将它存储在循环外声明的变量中。

StringBuilder sentence=new StringBuilder();
do {
    word = in.nextLine();
    count++;   
    System.out.print(" "+word);
    sentence.append(" "+word);
}
while (!word.equals(SENTINEL));

然后用于打印使用

System.out.println(sentence.toString());

答案 1 :(得分:1)

您可以使用StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html

分段阅读并将它们放在一起
StringBuffer sb = new StringBuffer();
do {
        sb.append( in.next() );
        count++;   
    }
    while (!word.equals(SENTINEL));

答案 2 :(得分:1)

您需要创建一个额外的字符串来“收集”用户输入的所有字词。您原件的问题是您将“word”替换为输入的单词。这应该可以解决问题:

import java.util.Scanner;

public class Chapter3ProblemsSet {

    public static void main(String [] args) {

    String word = "";
    String sentence = "";
    final String SENTINEL = "done";
    double count = 0; 

    String userInput = "";

    Scanner in = new Scanner (System.in);


    System.out.println("Please enter words: ");
    System.out.println("Enter done to finish.");
    word = in.next();

    do {
        word = in.next();
        count++;
        sentence += " " + word;


        System.out.print(" "+word);
    }
    while (!word.equals(SENTINEL));


    System.out.println(" "+sentence);

    }
}