我有这个字符串要返回,但是我不能,因为它说“ 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/