[英]working with streams problem of Local variable defined in an enclosing scope must be final
[英]Enclosing scope must be final with Java Streams
当尝试使用流计算字符串中的字符数时,出现错误“我在封闭范围内定义的局部变量必须是最终的或有效的最终”在这种情况下,您使用什么作为解决方法? 我只需要单独做而不循环吗? 我是一名学生,任务是解密凯撒密码,因此频率分析是其中的一部分。
谢谢你。
public static int[] freqAnalyse(String text) {
int[] frequencies = new int[26];
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text = text.toUpperCase();
for(int i = 0; i < 26; i++) {
frequencies[i] = (int) text.chars().filter(k -> k == alphabet.charAt(i)).count();
}
return frequencies;
}
编辑这有效,这是不好的做法还是它想要的? 谢谢你。
public static int[] freqAnalyse(String text) {
int[] frequencies = new int[26];
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text = text.toUpperCase();
for(int i = 0; i < 26; i++) {
final int j = i;
frequencies[j] = (int) text.chars().filter(k -> k == alphabet.charAt(j)).count();
}
return frequencies;
}
最简单的解决方法是将i
复制到一个新变量中。
final int ii = i;
frequencies[i] = (int) text.chars().filter(k -> k == alphabet.charAt(ii)).count();
或者,您可以只为该字符存储一个变量:
final char ch = alphabet.charAt(i);
frequencies[i] = (int) text.chars().filter(k -> k == ch).count();
在这些情况下,您也可以使用迭代器完全忽略计数变量i
。 这是另一种方法:
int[] frequencies = new int[26];
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text = text.toUpperCase();
for (char c : alphabet.toCharArray()) {
frequencies[c-'A'] = (int)text.chars().filter(value -> value == c).count();
}
仅使用流一个班轮:
String upperCase = text.toUpperCase();
alphabet.chars().forEach(ch -> frequencies[ch-'A'] = (int)upperCase.chars().filter(value -> value == ch).count());
也许你可以尝试做这样的事情:
public static int[] freqAnalyse(String text) {
int[] frequencies = new int[26];
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text = text.toUpperCase();
for(int i = 0; i < 26; i++) {
final char c = alphabet.charAt(i);
frequencies[i] = (int) text.chars().filter(k -> k == c).count();
}
return frequencies;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.