2

I want to say I'm new to Java so please don't hate me for my messy code. System.out.print("Enter your name") is not repeated if you will not enter anything on your keyboard. Loop goes around but this statement is not repeated. If you enter some letters the print statement is executed and I don't know why. Here is a picture to make it more clear. Probably it is a very easy mistake I made but I can't see it. Thanks for any help or clue how to solve this problem.

That's how it looks like:

Thats how it looks like

That's how I want it to be:

Thats how I want it to be

package loop;

import java.util.Scanner;
public class while_loop 
{
    public static void main(String[] args) 
    {
        String word2 = null;
        boolean T_F = true;
        while (T_F == true)
        {
            System.out.print("Enter your name:");
            Scanner in = new Scanner(System.in);
            word2 = in.next().toUpperCase();
            if (word2 != null && word2.length() > 3)
            {
                in.close();
                T_F = false;
                System.out.println("Done");
            }
        }
    }
}

Ehh OK solved. Small little mistake.

word2 = in.next().toUpperCase();

should be

word2 = in.nextLine().toUpperCase();
Matt
  • 27
  • 9
  • 1
    Read [this](http://stackoverflow.com/a/29690553/4677585) answer. Use `in.nextLine()` if you want `\n` to end the line. `in.next()` would not take an empty string. – wonderbell Mar 21 '16 at 20:38
  • This question has nothing whatsoever to do with soundex or most of the code you've posted. Please edit your question to narrow both the question and code to the actual problem (which is about reading lines using a scanner). – Bohemian Mar 21 '16 at 20:48
  • Thanks wonderbell. That is what I was looking for. Silly me ^^ – Matt Mar 21 '16 at 23:04

1 Answers1

0

Your if-statement should be:

if (!(word2 = in.nextLine().toUpperCase()).isEmpty() && word2.length() > 3){
     in.close();
     T_F = false;
}          

Scanner.next() will only return what comes before a space.

Scanner.nextLine() will automatically move the scanner down after reading the current line.

TheMirrox
  • 368
  • 2
  • 13
  • It had nothing to do with my If-statement but it is not your fault. I just asked my question in a wrong way. Thanks anyway – Matt Mar 21 '16 at 23:06