我的要求很简单,获取一个char位置并将其替换为另一个。
唯一要注意的是,char
和及其index
在运行时出现,并且不能进行硬编码。
我实际实现的虚拟代码:
public static void main(String args[])
{
StringBuilder sb = new StringBuilder("just going nuts") ;
System.out.println(" "+sb);
//System.out.println(sb.charAt(4)); //this works
sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0)); //line 8 -error line
System.out.println(" "+sb);
}
我什至尝试char
用引号括起来:
sb.setCharAt(sb.indexOf(( "\""+sb.charAt(4)+"\"" )), sb.charAt(0));
但仍然是相同的错误
错误
line no:8: cannot find symbol
symbol : method indexOf(char)
location: class java.lang.StringBuilder
sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0));
我不太熟练使用Java,但是找不到setCharAt
像这种情况下具有动态值的函数示例!
错误是因为indexOf
期望String
不是,char
所以您要做的就是将其包装String.valueOf
sb.setCharAt(sb.indexOf(String.valueOf((sb.charAt(4)))), sb.charAt(0));
输出
just going nuts
justjgoing nuts
当您键入甚至提供解决方案时(在IntelliJ以下),现代IDE应该会捕获此编译时错误:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句