с помощью сканера, как я могу получить один, имя ячейки которого содержит цифры и помет, как "A3, B2, C1" - PullRequest
0 голосов
/ 26 сентября 2018

как получить ввод двух символов на основе имени сетки, т. Е. «A3, B2, C1», другими словами, если ввод будет состоять только из двух символов, и один из них должен быть цифрой, а другой - пометой, есть ли лучший способ сделать эточто без использования этих ifs и elses?

обратите внимание: что не имеет значения, был ли ввод первым номером, он всегда будет проходить через помет, а затем числа

// поворачивая столбцы истроки для строки здесь только для проблем с поиском персонажа

private static boolean cellsChooser() {
    boolean flag = true;
    boolean getAnotherCell=false;
    char row = '-';
    int columns = -1;
    System.out.println("");
    System.out.println("Enter the cell you want to check");
    while (flag) {
        String stringCell = s.nextLine();
        //there five cases of the input
        // 1 if the user's input is more than 2 characters
        if (stringCell.trim().length() == 2) {
            // 2 if char -> int
            if (Character.isLetter(stringCell.charAt(0))) {
                row = stringCell.toUpperCase().charAt(0);
                if (Character.isDigit(stringCell.charAt(1))) {
                    columns = Integer.parseInt(stringCell.charAt(1) + "");
                    flag = false;
                    // 3 if char -> char
                    } else {
                    System.out.println("Sorry!\njust two characters one of 
                    them digit and the other alphabetic character  ");
                    continue;
                }
                // 4 if int -> char
            } else if (Character.isDigit(stringCell.charAt(0))) {
                columns = columns = Integer.parseInt(stringCell.charAt(0) +"");
                if (Character.isLetter(stringCell.charAt(1))) {
                    row = stringCell.toUpperCase().charAt(1);
                    flag = false;
                // 5 if int -> int
                } else {
                    System.out.println("Sorry!\njust two characters one of 
                    them digit and the other alphabetic character  ");
                    continue;
                }
            }
        }

1 Ответ

0 голосов
/ 26 сентября 2018

Вы можете использовать следующий код:

while (true) {
    System.out.println("Enter the cell you want to check");
    String stringCell = nameScanner.nextLine();

    if (stringCell != null && stringCell.trim().length() == 2) {
        if (Character.isLetter(stringCell.charAt(0)) && Character.isDigit(stringCell.charAt(1)))
                break;
    }

    System.err.println("Wrong input");
}

Здесь цикл прерывается, только если stringCell имеет длину 2 и если первый символ является буквой и если второй символ является цифрой,Это уменьшает объем вашего кода.

Надеюсь, это поможет.

...