Entering an empty string

Hey everyone! I'm trying to make really basic Java program that will tell me if the string I enter is empty, but I get an error if I start the program an press enter without entering anything. Any help would be appreciated!

//Shawn Nuckles

//Firday, January 26, 2007

//This program is used to determine if a string is a number, word, or empty

import java.util.Scanner;

publicclass Lab3Part1

{

publicstaticvoid main(String[] args)

{

Scanner keyboard =new Scanner(System.in);

System.out.println();//skip a line

System.out.print("Enter a string: ");

String WordOrNumber = keyboard.nextLine();

char FirstChar = WordOrNumber.charAt(0);//Assign FirstChar to the first character in the string

int Length = WordOrNumber.length();//Find the length of the strong so we can determine which character is the last

char LastChar = WordOrNumber.charAt(Length - 1);//Assign LastChar to the last character in the string

if (WordOrNumber =="")

{

System.out.println("Empty string.");

}

elseif (Character.isDigit(FirstChar) && Character.isDigit(LastChar))

{

System.out.println("\"" + WordOrNumber +"\"" +" is a number.");

}

elseif (Character.isLetter(FirstChar) && Character.isLetter(LastChar))

{

System.out.println("\"" + WordOrNumber +"\"" +"is a word.");

}

elseif ((Character.isLetter(FirstChar) && Character.isDigit(LastChar)) || (Character.isDigit(FirstChar) && Character.isLetter(LastChar)))

{

System.out.println("\"" + WordOrNumber +"\"" +" is something else.");

}

}

}

[3107 byte] By [Toji53a] at [2007-11-26 16:22:11]
# 1

You must compare Strings using .equals, not ==.

if (WordOrNumber == "")

should be:

if (WordOrNumber.equals(""))

or, for an empty String:

if (WordOrNumber.length()==0)

Note: you need to test for WordOrNumber having a length of 0 before you start pulling out characters from it. Otherwise, you'll get an exception.

doremifasollatidoa at 2007-7-8 22:45:58 > top of Java-index,Java Essentials,New To Java...
# 2

The reason why you need to use .equals()

is that == tests whether two pointers refer to the same object. Even if the contain the same text, two Strings are not necessarily the same object. The String class provides an overloaded equals function, which actually compares the contents of the string.

By the way, in Java, variables are conventionally named with the first letter lowercase.

PCUa at 2007-7-8 22:45:58 > top of Java-index,Java Essentials,New To Java...