简体   繁体   English

为什么它不让我在 java 中将字符串连接到整数?

[英]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.

相关问题 Java项目不会让我保存 - Java project won't let me save JDK-9不会让我使用字符串:“java.lang.String是不明确的”? - JDK-9 won't let me use Strings: “java.lang.String is ambiguous”? 为什么我的Java while循环不会停止并让我的程序终止? - Why won't my Java while loop stop and let me program terminate? 我正在尝试合并到整数字符串,但我正在使用的程序 Java 博士不允许我使用 ArrayUtils? - I am trying to merge to integer strings but Dr. Java the program I am using won't let me use ArrayUtils? Android工作室不会让我在字符串上使用开关? - Android studio won't let me use switch on a string? 为什么我的JTable不让我插入ImageIcon? - Why won't my JTable let me insert an ImageIcon? 为什么不让我使用泛型执行此类任务? - Why won't it let me perform this class assignment using generics? Netbeans 14 - 不让我激活 Java Web 和 EE - Netbeans 14 - Won't Let Me Activate Java Web and EE 为什么不能在Java中将Integer.toBinaryString()连接到另一个字符串? - Why can I not concatenate Integer.toBinaryString() to another string in Java? Java使我将变量声明为final,但随后不允许我对其进行写入 - Java makes me declare variable as final but then won't let me write to it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM