ABricker21
ABricker21

Reputation: 1

How do I limit the input to only 1 digit

I have the basic program written but, I need to make it so if more than one character is input an error message will show.

import java.util.Scanner;

public class VowelConsonant {
    public static void main(String [] args)
    {
        int i = 0;
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a letter from the alphabet");
        char ch = s.next().charAt(0);
        switch(ch)
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U': i++;
        }
        if (i == 1)
            System.out.println("The entered character " + ch + " is a vowel.");
        else
            if ((ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z'))
                System.out.println("The entered character "+ ch + " is a consonant.");
            else
                System.out.println("Error, not a letter in the alphabet");
    }
}

Upvotes: 0

Views: 907

Answers (2)

sanjeevRm
sanjeevRm

Reputation: 1606

You can validate if input is single letter as below

        Scanner s = new Scanner(System.in);
        System.out.println("Enter a letter from the alphabet");
        char ch = '\u0000'; //default value
        String input = s.next();
        if(input.length()==1) {
            System.out.println("Entered single char"+input);
            ch = input.charAt(0);
        } else {
            System.out.println("Entered more than one character"+input);
        }
        System.out.println("Entered character"+ch);

Upvotes: 2

Beru
Beru

Reputation: 673

You cannot prevent the user from entering an input String as follows for example, I will refuse to enter one character. However, you can validate the length of the input via the length() method.

String userInput = scanner.next();
if (userInput.length() != 1) {
    // Input is longer, what should I do?
}

With this you can then determine whether you accept the input or not.

Upvotes: 0

Related Questions