英文:
Incompatible Types at indexOf()
问题
我正在使用Java编写程序,但出现了一个错误。在hexnumber.indexOf(tempstring) 处,它给了我一个"不兼容的类型"错误信息。我感到困惑,因为我在前一行明确定义了tempstring为一个String对象。我应该如何解决这个问题?
String hexnumber = "0123456789ABCDEF";
String hexsolution = "";
int remainder = newDecNumber % 16;
String tempstring = Integer.toString(remainder);
hexsolution = hexsolution.concat(Integer.toString(hexnumber.indexOf(tempstring)));
newDecNumber = newDecNumber /= 16;
英文:
I'm writing a program in Java, but there appears to be an error. At hexnumber.indexOf(tempstring), it gave me the error message "incompatible types". I'm confused by this because I clearly defined tempstring to be a String object the line before. How should I fix this?
String hexnumber = "0123456789ABCDEF";
String hexsolution = "";
int remainder = newDecNumber % 16;
String tempstring = Integer.toString(remainder);
hexsolution.concat(hexnumber.indexOf(tempstring));
newDecNumber = newDecNumber /= 16;
答案1
得分: 2
尝试这段代码:
String hexnumber = "0123456789ABCDEF";
String hexsolution = "";
int remainder = newDecNumber % 16;
String tempstring = Integer.toString(remainder);
hexsolution = hexsolution.concat(hexnumber.substring(remainder, 1));
newDecNumber /= 16;
现在,concat() 函数的参数是 String 类型,因此不会出现类型错误。
而且 hexsolution 变量现在被正确地修改了,因为 concat() 函数不会直接修改变量。
英文:
Try this code:
String hexnumber = "0123456789ABCDEF";
String hexsolution = "";
int remainder = newDecNumber % 16;
String tempstring = Integer.toString(remainder);
hexsolution = hexsolution.concat(hexnumber.substring(remainder, 1));
newDecNumber /= 16;
Now, the concat() parameter is of String type, so there will be no error with types.
<br>
And the hexsolution variable is modified properly now, because concat() function does not modify directly the variable.
答案2
得分: 2
tdranv的评论是正确的 - String.concat()
接受一个String
参数并返回一个新的字符串。看起来你的意图是:
hexsolution = hexsolution.concat(hexnumber.substring(remainder, 1));
英文:
tdranv's comment is correct -- String.concat()
takes a String
argument and returns a new String. It looks like your intent is:
hexsolution = hexsolution.concat(hexnumber.substring(remainder, 1));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论