我有一个想要返回的字符串,但我不能,因为它说“print”无法解析为变量。这是我的代码:
public static String enrcyptText(String str, int shift){
int count = 0;
String[] parts = str.split("[\\W]");
for(String word : parts){
shift = shift * (count + 1) + 1;
count++;
encryptWord(word, shift);
String[] phrase = new String[]{word};
String print = String.join(" ", phrase);
}
return print;
}
有什么想法吗?
最佳答案
那里有几个问题。
您已声明
print
仅在循环体内。它不存在于它之外。所以你需要移动你的String print
在循环之外。您还在每次循环迭代中为其赋值,这将覆盖它之前的值。目前还不清楚您想做什么,但您不会想这样做。
这两行也没有任何意义:
String[] phrase = new String[]{word}; String print = String.join(" ", phrase);
因为
phrase
中只有一个条目,你最终会得到print
具有相同的值word
曾经。您似乎期望
encryptWord
可以修改传入其中的字符串。不可能。
尝试一下,我认为您的目标是“加密”句子中的各个单词,然后将结果重新组合成一组以空格分隔的加密单词。如果是这样,请参阅评论:
public static String enrcyptText(String str, int shift){
int count = 0;
String[] parts = str.split("[\\W]");
// For updating the array, better to use the classic
// for loop instead of the enhanced for loop
for (int i = 0; i < parts.length; ++i){
shift = shift * (count + 1) + 1;
count++; // Could do this before previous line and remove the + 1 in (count + 1)
parts[i] = encryptWord(parts[i], shift); // See note below
}
return String.join(" ", parts);
}
请注意,我使用的是 encryptWord
的返回值。这是因为 Java 中的字符串是不可变的(无法更改),因此 encryptWord
无法改变我们传递给它的内容;它只能给我们返回一个新的字符串来代替。
关于java - 如何打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32924678/