英文:
The operator + is undefined for the argument type(s) char[], int
问题
String x = "abcd";
Arrays.asList(x.toCharArray()).forEach(y -> System.out.println(y + 1));
// 这一行报错,因为 char[] 和 int 之间未定义 + 运算符。
Arrays.asList(new Integer[]{1, 2}).forEach(y -> {System.out.println(y + 1);});
// 对于整数,这样的操作是正常的。
当我们使用 `+` 运算符执行类似 `'a' + 1` 的操作时,我们得到 98,因为 'a' 的 ASCII 值是 97。
那么为什么在上述 char 数组的情况下不起作用呢?
你对此有何看法?
英文:
String x = "abcd";
Arrays.asList(x.toCharArray()).forEach(y -> System.out.println(y + 1));
// this line is giving an error that + operator is undefined for char[] and int.
Arrays.asList(new Integer[]{1, 2}).forEach(y -> {System.out.println(y + 1);});
// for integer it is working fine.
When we use + operator for doing something like this 'a' + 1 we get 98 because ASCII value of a is 97.
So why it is not working with char array in the above case.
Any thoughts on this?
答案1
得分: 3
Arrays.asList 将 x.toCharArray() 视为对象,因为 x.toCharArray() 返回 char[],所以它被视为一个元素,而你不能进行 char[] + int 的操作。为了解决这个问题,你可以使用 x.chars():
x.chars().forEach(y -> System.out.println(y + 1));
英文:
Arrays.asList consider x.toCharArray() as an object because x.toCharArray() return char[], so it is considers as one element, and you can't make char[] + int, to solve this you can use x.chars() :
x.chars().forEach(y -> System.out.println(y + 1));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论