首页 > 解决方案 > 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))))

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

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

标签: javaerror-handlingcompiler-errors

解决方案


if根据您的陈述,我认为您的问题就在这里:

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

让我们稍微扩展一下:

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

现在,positionis a StringformatString接受并返回 a Stringpositions[index]is a String,并equalsIgnoreCase比较Strings。所以,第一行很好。

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

我认为放弃外部调用formatString会解决您的问题。顺便说一句,里面的三元运算符formatString是不必要的,因为 "".trim().equals("")。呃,既然你在使用equalsIgnoreCasetoUpperCaseinformatString也是多余的,所以为什么不只是

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

?

更新formatString最初没有提供。现在已经重写了这个答案。


推荐阅读