0

I've got a loop that is controlled by a variable called running which tells if the program is running or not. I am trying to achieve a loop that the user enters a command, and the program is answering him, but for some reason, It's seems like my String splits if its more than one word, this is what I have tried:

import java.util.Scanner;
public class ScannerTest{
    private boolean running = true;
    public ScannerTest(){
        Scanner s = new Scanner(System.in);
        while(running){
           String command = s.next();
           System.out.println(command);
        }
    }
}

If I am entering two or more words in the Scanner, It seems to split them.

Input  >> Hello what's your name?
Output >> Hello
       >> what's
       >> your
       >> name?

Maybe it's because of the While loop? How can i fix it? Thanks in advance.

4 Answers 4

4

Scanner#next() does just this -- it grabs the next token defined by any white-space delimiter(s), and does not get the next line. If your words have white space between them, it will grab the individual words one at a time with each invocation of the method.

Use Scanner#nextLine() instead if you want to grab the complete line that the user entered.

Edit: this question has to be a duplicate of another somewhere on this site.

Sign up to request clarification or add additional context in comments.

Comments

0

next() method will split your input by space delimiter.

nextLine() method will fix your problem. nextLine(); will read the entire line at once.

Replace String command = s.next(); to String command = s.nextLine();

1 Comment

But how does this work if you need to get integer inputs in a loop? I noticed that nextInt seems to skip an input because of a RETURN character (I presume).
0

You're using

System.out.println();

just use

System.out.print();

only use println if you want the next output/input to be entered onto the next line.

Comments

0

Why don't you use end-of-file indicator, the loop you used in your solution is called sentinel-controlled repetition the I think the better value to control it is by using end-of-file indicator take look at my answer java Scanner.hasNext() usage

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.