【问题标题】:The operator + is undefined for the argument type(s) char[], int运算符 + 未定义参数类型 char[], int
【发布时间】:2020-09-10 07:25:33
【问题描述】:
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.

当我们使用+ 操作符来执行类似'a' + 1 的操作时,我们会得到 98,因为 a 的 ASCII 值是 97。 那么为什么在上述情况下它不能与 char 数组一起使用。

对此有什么想法吗?

【问题讨论】:

  • Arrays.asList(x.toCharArray()) 将返回 List<char[]> 而不是 List<char>List<Character>
  • 您误解了Arrays.asList(x.toCharArray()) 的作用。它创建一个包含一个元素的流:char 数组。它不会创建单个字符的流。

标签: java string char


【解决方案1】:

Arrays.asListx.toCharArray() 视为一个对象,因为x.toCharArray() 返回char[],所以它被视为一个元素,您不能制作char[] + int,要解决此问题,您可以使用x.chars()

x.chars().forEach(y -> System.out.println(y + 1));

【讨论】:

  • 或者干脆for(char y : x.toCharArray()) { System.out.println(y + 1); }
  • @Lino 我同意,但 OP 使用 forEach :)
猜你喜欢
  • 2017-06-04
  • 1970-01-01
  • 2018-06-30
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多