user4099200
user4099200

Reputation:

Having trouble with Character.isWhiteSpace() in Java

I have this one problem for homework that I need to solve. The code is working fine, except for the white space option. NetBeans gives me a warning when I use .isWhiteSpace, but it goes away when I use .isWhitespace. Either way, when I run the program and enter a space or a tab, the program just keeps running, completely ignoring it. Any suggestions?

package problemset3;
import java.util.Scanner;

public class ProblemSet3
{

    public static void main(String[] args)
    {
      Scanner in = new Scanner(System.in);

      System.out.print("Enter a character: ");
      String userString = in.next();
      char userChar = userString.charAt(0);


        if (Character.isDigit(userChar))
        {
          System.out.println("Character is a number.");    
        }
        else if (Character.isLetter(userChar))
        {
         if (Character.isUpperCase(userChar))
         {
             System.out.println("Character is an upper case letter");
         }
         else
         {
             System.out.println("Character is a lower case letter");
         }
        }
        else if (Character.isWhitespace(userChar))
        {
            System.out.println("Character is white space.");
        }
        else
        {
          System.out.println("Character is unknown");
        }
    }
}

Upvotes: 1

Views: 1979

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502246

The problem is your use of Scanner.next():

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

The default delimiter for Scanner is whitespace - so it isn't going to return whitespace.

You might want to use nextLine instead... but be aware that if the user just presses return, the line will be empty, so charAt(0) will throw an exception.

Upvotes: 3

Related Questions