Caleb Owusu-Yianoma
Caleb Owusu-Yianoma

Reputation: 376

How can I determine if user's input is empty?

I am writing code to generate a JavaCC parser, which will read a user's input and check if it is in any one of a set of languages defined in my code.

One condition on allowable input is that it must not be empty - i.e., the user must enter some block of characters (with length greater than or equal to 1) other than white space " ".

I would like to be able to determine if the user's input is empty, so that an error message can be printed out on the screen in that case.

I have written a production (a.k.a rule) that gets the user's input; it's called Input() and is declared to be void. In the main method, I have tried to write code which determines if the user's input is empty, by writing:

if parser.Input() == null {
  // print error message onto the screen
}

However, I get an error message on the terminal when I try to compile, stating that a 'void' type is not allowed here (I am sure this is referring to Input).

Could I please have a hint/hints for getting around this issue?

Upvotes: 0

Views: 93

Answers (2)

Theodore Norvell
Theodore Norvell

Reputation: 16221

Write the Input production like this

boolean Input() : {
} {
    <EOF>
    {return true;}
|
   ... // other possibilities here
   {return false;}
}

Then, in the main method, you can write

if( parser.Input() ) {
    ... // report error
}

This solves the problem of reporting the error.

However you may also want to report the language found. For that you could make an enumeration type and have Input return a member of the enumeration. EMPTY could be one of the possibilities.

Language lang = parser.Input() ;
switch( lang ) {
    case EMPTY:
        ... // report error
    break ;
    case LANGA:
        ...
    break ; 
    ... // etc.
}

Upvotes: 2

salembo
salembo

Reputation: 11

Change your type method so this can return a value and you can validate the result, when you do this but change the comparison like this:

if null==parser.Input(){ //print error message on screen }

Another option is to validate data inside your Input method so you keep it like void.

Upvotes: 1

Related Questions