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.

Orel Bitton
  • 547
  • 1
  • 6
  • 11

4 Answers4

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
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();

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 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). – itsols Nov 12 '14 at 12:42
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.

Mazino
  • 552
  • 6
  • 27
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

Community
  • 1
  • 1
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92