FUBAR
FUBAR

Reputation: 9

Validating a single character JAVA

I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.

Here's my code I have thus far:

static char getCustomerType() {
    System.out.println("Please enter the term for the Policy the client would like");
    System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");

    String s = inputs.next();

    while (s != 'A' && s != 'M') {
        System.out.println("Incorrect, please try again");
        s = inputs.next();
    }
}

Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement? It also doesn't like the while statement producing incompatible string type referencing boolean to string.

I assume this is because I have declared s as a String?

Upvotes: 0

Views: 2664

Answers (2)

martin
martin

Reputation: 11

why not write

while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false) 

Upvotes: 1

Arvind Gupta
Arvind Gupta

Reputation: 63

You can have single characeter input from user using below code assuming inputs is your scanner object:

char c = inputs.next(".").charAt(0);

and then you can compare it using != or .equals() or .equalsIgnoreCase()

Upvotes: 1

Related Questions