Логическая ошибка в Java, преобразованная в строку - PullRequest
0 голосов
/ 12 апреля 2019
Main.java:138: error: incompatible types: boolean cannot be converted to String
            if(formatString(positions[index].equalsIgnoreCase(formatString(position))))
                                                             ^
Main.java:160: error: incompatible types: boolean cannot be converted to String
            if(formatString(players[index].equalsIgnoreCase(formatString(player))))

Выше приведены ошибки. Я хотел бы знать, где логическое значение изменяется на String.

formatString () является методом позиции [] это массив строк

 /**
 * Method that finds the index of player by using the position
 *
 * @param   position    The position of the baseball player
 * @return     The index of the player at a certain position
 */
public int findIndex(String position)
{
    int index = 0;
    while(index < positions.length)
    {
        if(formatString(positions[index].equalsIgnoreCase(formatString(position))))
        {
            return index;
        }
        else
        {
            return -1;
        }
    }
}

/**
 * Method that finds the player position by finding the name
 *
 * @param   player  The namee of the player
 * @return     The position that matches the players name
 */
public String findPlayerPosition(String player)
{
    int index = 0;
    while(index < players.length)
    {
        if(formatString(players[index].equalsIgnoreCase(formatString(player))))
        {
            return positions[index];
        }
        else
        {
            return "NONE";
        }
    }
}

Метод formatString ()

public String formatString(String oldString)
        {
             return (oldString.equals("") ? oldString : (oldString.trim()).toUpperCase());
        }

Метод formatString () выполняет обрезку () и верхний регистр () строки, передаваемой через параметр.

1 Ответ

0 голосов
/ 12 апреля 2019

Я думаю, что ваша проблема здесь, в состоянии вашего if заявления:

if(formatString(positions[index].equalsIgnoreCase(formatString(position)))

Давайте немного расширим это:

final boolean equivalent = positions[index].equalsIgnoreCase(formatString(position));
final boolean condition = formatString(equivalent);
if (condition) {
    // ...
}

Теперь position - это String, formatString принимает и возвращает String, positions[index] - это String, а equalsIgnoreCase сравнивает String с. Итак, первая строка в порядке.

Вторая строка, однако ... в развернутом виде ясно, что вы пытаетесь вызвать formatString с boolean. Мы знаем, что он должен принимать String, так что это ошибка, о которой сообщается. Есть и другая проблема - formatString возвращает a String, но, поскольку вы используете его в качестве условия оператора if, это должен быть boolean.

Я думаю, что отказ от внешнего вызова на formatString решит вашу проблему. Кроме того, троичный оператор внутри formatString не нужен, так как "" .trim (). Equals (""). А так как вы используете equalsIgnoreCase, toUpperCase в formatString также является избыточным, так почему бы просто не

if (positions[index].equalsIgnoreCase(position))

Обновление : formatString изначально не было предоставлено. Этот ответ был переписан теперь, когда он был.

...