0

This is what I have so far. I want the program to print out the words the user inputs as a sentence. But I don't know how I get that to happen with the code I have written so far. ex: if you entered Hello World done

The program should say: "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);

    }
}
2
  • You know scanner has a nextLine() function right? Commented Oct 14, 2014 at 19:49
  • Homework hint: define a variable scoped to your main method, add user input to the variable (String.concat() is one way), and output to screen. Commented Oct 14, 2014 at 19:50

3 Answers 3

2

What you need it to store it in a variable which is declared outside the loop.

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

Then for printing use

System.out.println(sentence.toString());
Sign up to request clarification or add additional context in comments.

Comments

2

You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:

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

    }
}

Comments

1

You can read it by pieces and put them together using a 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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.