Luke Harding
Luke Harding

Reputation: 105

Combing user-entered words into a sentence

I am trying to write a program that takes words entered by the user and builds a sentence using those words. So if you enter "Hello" and "World", it will return "Hello World." However if I enter "I", "love", and "dogs", it will return " love dogs done." (done is my sentinel for the user to quit. I'm not sure how to do this.

import java.util.Scanner;

public class SentenceBuilder {


public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);

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

    System.out.println("Enter multiple words: ");
    System.out.println("Enter done to finish: ");
        word = scnr.nextLine();


    do {
        word = scnr.nextLine();
        count++;
        sentence += word + " ";
    } while (!(word.equalsIgnoreCase(SENTINEL)));



    System.out.println(sentence);
}

}

Upvotes: 0

Views: 163

Answers (2)

user3437460
user3437460

Reputation: 17454

Change your codes to the following:

public static void main(String[] args)
{ 
    Scanner scnr = new Scanner(System.in);

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

    System.out.println("Enter multiple words: ");
    System.out.println("Enter done to finish: ");
    //remove the first prompt here..
    do {
        word = scnr.next();
        if(word.equalsIgnoreCase(SENTINEL))  //exit loop if "done" was input
            break;          
        count++;
        sentence += word + " ";
    } while (!(word.equalsIgnoreCase(SENTINEL)));

    System.out.println(sentence);           
}

You need to remove the first prompt outside your loop, if not it won't add the first input into your string. I added a check to break out once "done" is received.

This is probably a question from school, hence you uses sentence += word. However, for accumulatively adding to strings, it is better to use a StringBuilder though.

Upvotes: 1

Srinivasan A
Srinivasan A

Reputation: 73

Just re-write your do while block in a simple way.

    word = scnr.nextLine();
    while (!(SENTINEL.equalsIgnoreCase(word))) {
        sentence += word + " ";
        word = scnr.nextLine();
        count++;
    } 

Upvotes: 0

Related Questions