[英]Why won't it let me concatenate a string to an integer in java?
So, I have this for loop, at the end of which I attempt to concatenate an integer to a string to an integer, like so:所以,我有这个 for 循环,最后我尝试将一个整数连接到一个字符串到一个整数,如下所示:
int a = 0;
for (int i = 0; i < userResponses.length; i++) {
if (userResponses[i].equals(correctAnswers[i]))
a++;
return a + ("/") + correctAnswers.length;
}
It gives me an incompatible types error.它给了我一个不兼容的类型错误。 That seems really weird as I thought Strings and ints could be concatenated.
这看起来真的很奇怪,因为我认为 Strings 和 ints 可以连接起来。 Here's the exact error:
这是确切的错误:
TriviaTest.java:51: error: incompatible types
} return a + ("/") + correctAnswers.length;
^
required: int
found: String
1 error
From what I observe, the problem is with the return statement.据我观察,问题出在 return 语句上。
There is nothing wrong with the concatenation expression itself.连接表达式本身没有任何问题。 It would work if you printed it, for example.
例如,如果您打印它,它将起作用。 It sounds very much like your method's return type is
int
, so it can't return a String.听起来很像您的方法的返回类型是
int
,因此它不能返回字符串。
Also it looks a bit strange where you seem to have the return statement unconditionally in the loop.此外,您似乎在循环中无条件地拥有 return 语句,这看起来有点奇怪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.