ClownInTheMoon
ClownInTheMoon

Reputation: 225

Basic console input and output

I'm looking for a way to basically give back to the user some console output that looks identical to what they type and then prompt again for more input. The problem is I have a method that modifies each String discovered that does not consist of white space.

At the end of each sentence given by the user, I am trying to figure out a way to get a newline to occur and then for the prompt to output to the console again saying "Please type in a sentence: ". Here is what I have so far...

System.out.print("Please type in a sentence: ");

    while(in.hasNext()) {
        strInput = in.next();

        System.out.print(scramble(strInput) + " ");


        if(strInput.equals("q")) {
            System.out.println("Exiting program... ");
            break;
        }

    }

Here is what is displaying as console output:

Please type in a sentence: Hello this is a test
Hello tihs is a tset 

And the cursor stops on the same line as "tset" in the above example.

What I want to happen is:

Please type in a sentence: Hello this is a test
Hello tihs is a tset
Please type in a sentence: 

With the cursor appearing on the same line as and directly after "sentence:"

Hopefully that helps clear up my question.

Upvotes: 1

Views: 121

Answers (2)

nhouser9
nhouser9

Reputation: 6780

Try this, I didn't test it but it should do what you want. Comments in the code explain each line I added:

while (true) {
    System.out.print("Please type in a sentence: ");
    String input = in.nextLine(); //get the input

    if (input.equals("quit")) {
        System.out.println("Exiting program... ");
        break;
    }

    String[] inputLineWords = input.split(" "); //split the string into an array of words
    for (String word : inputLineWords) {        //for each word
        System.out.print(scramble(word) + " "); //print the scramble followed by a space
    }
    System.out.println(); //after printing the whole line, go to a new line
}

Upvotes: 1

Ajoy Bhatia
Ajoy Bhatia

Reputation: 623

How about the following?

while (true) {
    System.out.print("Please type in a sentence: ");

    while (in.hasNext()) {
        strInput = in.next();

        if (strInput.equals("q")) {
            System.out.println("Exiting program... ");
            break;
        }
        System.out.println(scramble(strInput) + " ");
    }
    break;
}

The changes are:

  1. You should be printing "Please type in a sentence: " inside a loop to have it print again.
  2. I think you want to check if the strInput is "q" and exit BEFORE printing it, i.e. no need to print the "q", or is there?
  3. Use println to print the scrambled strInput so that the next "Please type in a sentence: " appears in the next line, and the cursor appears on the same line as " ... sentence: " because that is output by System.out.print (no ln)

Upvotes: 0

Related Questions