尽管在函数内对其进行了更改,该函数仍返回不变的输入

时间:2019-03-06 07:27:22

标签: java function arguments

仅就以下代码而言,我遇到了一个问题,即一切运行正常,但没有得到所需的输出。

该代码应接受用户输入并打印,但所有字母的大写都应颠倒。但是,即使将输入返回到toggleStringCase后,toggleCase仍能正常工作,它仍会恢复为发送至toggleCase之前的状态。

我无法理解为什么会发生这种情况。

有人能指出我正确的方向吗?

理想情况下,我不希望您告诉我答案,而只是帮助我以正确的方式解决此问题。

package loopy;
import java.io.*;

public class loopy {
    public static void main (String[] args) throws IOException {
        // TODO: Use a loop to print every upper case letter
        for (int i = 65; i < 91; i++) {
            System.out.println((char)i);
        }
        // TODO: Get input from user. Print the same input back but with cases swapped. Use the helper functions below.
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        String input = in.readLine();
        in.close();     

        toggleStringCase(input);

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        out.write(input);
        out.close();
    }

    //Takes a single Character and reverse the case if it is a letter
    private static char toggleCase(char c) {
        int asciiValue = (int) c;
        if (asciiValue > 96 && asciiValue < 123){
            asciiValue = asciiValue - 32;
        }
        else if (asciiValue > 64 && asciiValue < 91){
            asciiValue = asciiValue + 32;
        }
        else {

        }
        c = (char) asciiValue;
        return c;
    }

    // Splits a string into individual characters that are sent to toggleCase to have their case changed
    private static String toggleStringCase(String str) {
        String reversedCase = new String();
        for (int i = 0; i < str.length(); i++) {
            char letter = str.charAt(i);
            toggleCase(letter);
            reversedCase = reversedCase + letter;
        }
        str = reversedCase;
        return str;
    }
}

2 个答案:

答案 0 :(得分:4)

toggleStringCase(input);

我认为您可能想获取该函数的输出。您似乎假设输入将被更改-事实并非如此。参见Is Java "pass-by-reference" or "pass-by-value"?

答案 1 :(得分:3)

Java中的参数按值传递。您不能以这种方式更改传递给方法的值。但是,您正在返回所需的值-只需将其分配回您的变量即可:

input = toggleStringCase(input);