0
Scanner input = new Scanner(System.in);
boolean flag = true;

System.out.print("What is your name? ");
flag = true;
while(flag == true){
    name = input.next();
    fullName = fullName + " " + name;
    if(input.hasNext() == false){
        flag = false;
    }
} 

The above code is just a sample of my whole program, but this piece of the code is where I am having problems.

With the above code, the input that I enter into the console is "the one". The problem is after input.next() collects "one" and then adds it to fullName, when the code goes to the if statement to check if there is more input (which there is none), the program just hangs. I am using BlueJ and the program debugger says that the thread is still running but nothing is going on. I'm wondering how do I collect the entire input of "the one" using a Scanner?

Pardeep
  • 712
  • 8
  • 17
  • Can you not just put input.hasNext() as you while condition? eg. while(input.hasNext()){ – Blue Boy Apr 28 '17 at 03:04
  • No. After the last input, once the program goes to check input.hasNext() the final time the program just hangs. Bluej debugger says that the thread is running, but I can't step forward into the code and their is no error showing up. – thankgodforthissite Apr 28 '17 at 03:12

2 Answers2

3

I suggest you to use

if(!input.hasNext()){
    flag = false;
}

Rather than using

if(input.hasNext() == false){
    flag = false;
}
0

Use name = input.nextLine();

Refer: What's the difference between next() and nextLine() methods from Scanner class?

Java doc Scanner

next() Finds and returns the next complete token from this scanner.

nextLine() Advances this scanner past the current line and returns the input that was skipped.

while (true) {
    name = input.nextLine();
    if(name.length() == 0){
        break;
    }
    fullName = fullName + " " + name;
}
Community
  • 1
  • 1
Devendra Lattu
  • 2,532
  • 2
  • 15
  • 25