ClownInTheMoon ClownInTheMoon - 2 months ago 8
Java Question

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.

Answer

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
}