Java中的布尔错误转换为字符串

时间:2019-04-11 23:32:08

标签: java error-handling compiler-errors

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))))

以上是错误。我想知道布尔值在哪里更改为字符串。

formatString()是一个方法 position []是一个字符串数组

 /**
 * 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 个答案:

答案 0 :(得分:0)

在您的if声明中,我认为您的问题就在这里:

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

让我们稍微扩展一下:

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

现在,positionStringformatString接受并返回Stringpositions[index]String,而{{1 }}比较equalsIgnoreCase s。因此,第一行就可以了。

第二行,但是,在展开形式中,很明显,您正在尝试使用String来调用formatString。我们知道它应该接受boolean,所以这就是所报告的错误。尽管还有另一个问题-String 返回一个formatString,但是由于您将其用作String语句的条件,因此它必须是if

我认为将外部呼叫置于boolean会解决您的问题。顺便说一句,formatString内部的三元运算符是不必要的,因为“” .trim()。equals(“”)。嗯,由于您使用的是formatStringequalsIgnoreCase中的toUpperCase也是多余的,所以为什么不

formatString

更新:最初未提供if (positions[index].equalsIgnoreCase(position)) 。答案已经被重写。