java - 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()。
解决方案
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
informatString
也是多余的,所以为什么不只是
if (positions[index].equalsIgnoreCase(position))
?
更新:formatString
最初没有提供。现在已经重写了这个答案。
推荐阅读
- spring-boot - SpringBoot中的@Putmapping删除关系对象
- node.js - 当我尝试保存对象数组时出现猫鼬验证错误
- python - Django Ajax 表单提交两次
- laravel - Laravel 6 数据库通知在生产中不起作用
- r - 如何根据单独的列变量汇总列?
- ios - 颤振横幅广告在真实设备上不起作用
- python - 熊猫应用功能不起作用并且没有任何错误
- stripe-payments - Stripe - 使用时间表在期末降级
- c++ - opencv连接细线
- mysql - 为什么 MariaDB 拒绝创建一个错误 [42000][1064] 的简单表?