Is there a char.length command?

TragicFlawz :

// I am stuck trying to get my program to only accept a single character from the scanner. Right now the program will accept any amount of characters as long as the first letter is one of the listed letters. I would like to rewrite this code with out the charAt(0) if possible or to add a if statement. if(sea.length > 1){} something like that. I hope I explained the issue well enough to understand. Any help is appreciated, and thank you for your time.

    public static char promptForChoice(Scanner in) {

    System.out.println("High, Low or Seven(H/L/S");
    char sel = in.next().charAt(0);
    sel = Character.toUpperCase(sel);
    int i = 1;
    while (i != 0) {
        System.out.println("High, Low or Seven(H/L/S");
        if (sel == 'H' || sel == 'L' || sel == 'S') {
            i = 0;
        } else {
            System.out.println("You must enter only H, L or S.");
            i = 1;
        }
    }
    return sel;


} 
Arvind Kumar Avinash :

Is there a char.length command?

No, there is no such command. You need to get the input using Scanner::nextLine() and check the length of the input String.

Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Test
        Scanner in = new Scanner(System.in);
        System.out.println(promptForChoice(in));
    }

    public static char promptForChoice(Scanner in) {
        char sel = 0;
        String input;
        boolean valid;
        do {
            valid = true;
            System.out.print("Enter H/L/S [High/Low/Seven]: ");
            try {
                input = in.nextLine();
                sel = input.toUpperCase().charAt(0);
                if (input.length() == 1 && (sel == 'H' || sel == 'L' || sel == 'S')) {
                    return sel;
                } else {
                    throw new IllegalArgumentException("You must enter only H, L or S.");
                }
            } catch (IllegalArgumentException e) {
                valid = false;
                System.out.println(e.getMessage());
            }
        } while (!valid);
        return sel;
    }
}

A sample run:

Enter H/L/S [High/Low/Seven]: hello
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: High
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: M
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: H
H

Feel free to comment in case of any doubt/issue.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374658&siteId=1