#java #error-handling #compiler-errors
#java #обработка ошибок #ошибки компилятора
Вопрос:
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() — это метод positions[] — это массив строк
/**
* 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() выполняет trim() и uppercase() для строки, переданной через параметр.
Комментарии:
1. Показать
formatString
. Похоже, он возвращает bool.
Ответ №1:
Я думаю, что ваша проблема здесь, в условии вашего if
утверждения:
if(formatString(positions[index].equalsIgnoreCase(formatString(position)))
Давайте немного расширим это:
final boolean equivalent = positions[index].equalsIgnoreCase(formatString(position));
final boolean condition = formatString(equivalent);
if (condition) {
// ...
}
Теперь position
is a String
, formatString
принимает и возвращает a String
, positions[index]
is a String
и equalsIgnoreCase
сравнивает String
s . Итак, первая строка в порядке.
Однако вторая строка… в развернутом виде ясно, что вы пытаетесь вызвать formatString
с boolean
помощью . Мы знаем, что он должен принимать a String
, так что это ошибка, о которой сообщается. Однако есть еще одна проблема — formatString
возвращает a String
, но поскольку вы используете его как условие if
оператора, оно должно быть a boolean
.
Я думаю, что удаление внешнего вызова formatString
решит вашу проблему. Кроме того, троичный оператор внутри formatString
не нужен, поскольку «».trim().equals(«») . Э, и поскольку вы используете equalsIgnoreCase
, toUpperCase
in formatString
также является избыточным, так почему бы просто не
if (positions[index].equalsIgnoreCase(position))
?
Обновление: formatString
изначально не было предоставлено. Этот ответ был переписан теперь, когда он был.
Комментарии:
1. Добавлен метод FormatString(). Может быть, проблема в заголовке?
2. @ParthSPatel Я переписал ответ с этой новой информацией.