如何打印字符串

How to print String

我有这个字符串,我想 return 但我不能,因为它说 "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 变量在 braces.You 内有作用域应该将 print 变量移到大括号外以使其对 code.Also 可见,因为它是一个局部变量,打印应该用默认值初始化(在我的例子中,它是空的)。编译器会抱怨打印保持未初始化(虽然这与主要问题无关)

public static String enrcyptText(String str, int shift){
        int count = 0;
        String[] parts = str.split("[\W]");
        String print = null;
        for(String word : parts){ 
                shift = shift * (count + 1) + 1;
                count++;
                encryptWord(word, shift);
                String[] phrase = new String[]{word};
                print = String.join(" ", phrase);
            }
        return print;
    }

那里有几个问题。

  1. 您只在循环体内声明了print。它不存在于它之外。因此,您需要将 String print 移到 循环之外。

  2. 您还在每次循环迭代中分配给它,这将覆盖它之前的值。目前还不清楚你想做什么,但你不会想要那样做。

  3. 这两行也没有任何意义:

    String[] phrase = new String[]{word};
    String print = String.join(" ", phrase);
    

    由于 phrase 中只有一个条目,您最终会得到 print 具有与 word 相同的值。

  4. 你似乎期望encryptWord可以修改传递给它的字符串。不能。

尝试一下,我认为您的目标是 "encrypt" 句子中的单个单词,然后将结果重新组合成一组 space 分隔的加密单词。如果是这样,请参阅评论:

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 中的 return 值。那是因为 Java 中的字符串是 immutable(无法更改),因此 encryptWord 无法更改我们传递给它的内容;它只能给我们一个新的字符串来代替。

您的代码存在逻辑错误:您正确地加密了每个单词,但没有正确构建加密的短语。在循环的每次迭代中,当您应该向 phrase 数组添加元素时,您正在重新创建短语。

public static String enrcyptText(String str, int shift) {
    int count = 0;
    String[] parts = str.split("[\W]");
    String[] phrase = new String[parts.length]; // initialising an array containing each encrypted word
    for (String word : parts) {
        shift = shift * (count + 1) + 1;
        count++;
        String encryptedWord = encryptWord(word, shift);
        phrase[count - 1] =  encryptedWord; // updating the encrypted phrase array
    }
    return String.join(" ", phrase); // joining the phrase array
}

在这段代码中,我们在循环之前创建了一个 phrase 数组。在每次迭代中,我们用加密的词更新这个数组。当我们拥有所有加密的单词时,循环终止,我们将所有部分连接在一起。

我也在猜测 encryptedWord 实际上是 returns 加密的词。此方法不能修改作为参数给定的单词。