0

I'm trying to make a java function take some input, change it and send it back. Normally you would have return varName; or something however here it is not working. My question is this: how can I make a custom method to take in a variable 'nameRaw' and change it within the function 'nameChanger()' then out put the changed name to variable: 'nameChanged'.

I have used IDEONE.com to show the code and process it, so here is the link: http://ideone.com/cdj6Cd

If you do not trust random links, that's find and completely understandable. So, I'll also put it here but just assume the only thing the user has typed as the input is "Test".

Code:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception {
        System.out.println("*INTENDED* Function of this-To create a custom method to take in a variable 'nameRaw' and change it within the function 'nameChanger()' then out put the changed name to variable: 'nameChanged'.\nProblem: the name changes within the function 'nameChanger()' only, therefore I cannot call the variable 'nameChanged' elsewhere, such as in main().........\n\n\n");
        // Initalize the Java Scanner
        Scanner in = new Scanner(System.in);

        // Initalizes a completely empty string with name "nameChanged"
        String nameChanged = null;

        System.out.println("Please enter a username for yourself below:");
        System.out.println("Test"); // Fake input to make me feel good I guess, it just looks better

        // Sets "nameRaw" to "Test"
        String nameRaw = in.nextLine();

        // Spits out the untouched value that the user has entered
        System.out.println("\nRaw name before passing to custom method: " + nameRaw);

        // Puts "nameRaw" into the custom method "nameChanger()" to change the, "s" in, "Test" to a "z" by default
        nameChanger(nameRaw, nameChanged);

        // Spits out the touched and changed nameChanged variable from "nameChanger()"
        if(nameChanged == null) {
            System.out.println("\nHere is the failed changed name: " + nameChanged);
            System.out.println("\nARE YOU KIDDING ME! WHY DOES THIS NOT WORK?!?! PLEASE HELP!!!!");
        } else {
            System.out.println("Here is the successfuly changed name: " + nameChanged);
            System.out.println("\nWhoever solved this problem is a god..");
        }

    } // Closes method main()

    // Custom method named "nameChanger" that will need a variable named "nameRaw" *which is set* within its () to function
    private static String nameChanger(String nameRaw, String nameChanged) {

        //// Initalizes a completely empty string with name "nameChanged"
        //String nameChanged = null;

        // States the set name *unchanged* from the main method on line 17
        System.out.println("\t#\tName unchanged read and displayed by the nameChanger custom method: " + nameRaw);

        // The name by default "Test" does contain an "s" so the if statement is satisfied
        if(nameRaw.contains("s")) {

            // The variable "nameRaw should be running through here and having it's "s" replaced with a "z"
            nameChanged = nameRaw.replace("s", "z");

            // Output the changed name *if all goes right*
            System.out.println("\t#\tName changed *still in custom function* is: " + nameChanged);

        // The else statement is just for testing purposes, such as changing "Test" as the input to "Demo" to dis-satisfy the if statemtent 
        } else {
            System.out.println("\t#\tFor reference, here is the unchanged name raw: " + nameRaw);
            System.out.println("\t#\tAlso for reference, here is the null value 'nameChanged': " + nameChanged);
        }

        // One more time to show my hate toward Java, output the changed variable "nameChanged". Take note that the "s" is a "z".....
        System.out.println("\t#\tPlease don't be null or have an 's' in it: " + nameChanged);

        // To output to main() that nameChanged is now not null *if all goes right*, but "Tezt" should be the output
        return nameChanged;
    } // Close custom method, nameChanger()
}

Thanks guys hope this doesn't overwhelm you toooo much :p, Aaron

Aaron Belz
  • 67
  • 7

7 Answers7

0

Short answer: You need to do this in your main method:

nameChanged = nameChanger(nameRaw, nameChanged);

Explanation: If you change the value that an object reference points to in a different method, the change will not be visible to the calling method. In your case, nameChanged is declared in the main method and being reassigned in the nameChanger method, and hence, the change is not visible in the main method.

You can however modify an object by calling it's mutable methods:

// in the main method
SomeStudent s = new SomeStudent();
modifyStudent(s);

// inside modifyStudent method
// change will be visible in the main method
s.setResult("PASS");

and the change will be visible in the main method.

However, in your case this is not possible, because Strings in Java are immutable. Hence, you need to return the modified string and capture the returned value in the main method.

Also, you don't need to pass nameChanged into nameChanger, for the reasons explained above.

rohitvats
  • 1,811
  • 13
  • 11
0

Since in Java method calls are always call-by-value, you can not change variables outside of your current block (e.g. method) as you could by using pointer in C. You would need to either use a return value and assign it to the variable

nameChanged = nameChanger(nameRaw, nameChanged);

or create some form of holder object which internally manipulates a variable.

Community
  • 1
  • 1
Daniel Hintze
  • 447
  • 3
  • 8
0

You're trying to change the variable via side effects. Note that when you call nameChanger() you don't actually assign the return value to a variable.

String result = nameChanger(nameRaw) is a more direct way to approach it. It is generally not desirable to rely on side effects. Note that I also changed the method signature because you now don't need to pass it a variable that you want the results stored in, you can create that within the scope of your method.

public static String nameChanger(String nameRaw) {
    String result = "";
    // do stuff
    if(nameRaw.contains("s")) {
        result = nameRaw.replace("s", "z");
    }
    //more stuff and System.out.println() statements
    return result;
}
James
  • 903
  • 7
  • 22
0

You don't pass the variable that is subject to change. Instead, change your code to the following method call in main():

String nameChanged = nameChanger(nameRaw);

and create the variable you want to return in the method you are actually creating it:

private static String nameChanger(String nameRaw) {
    String nameChanged = null; //
    // ...
    // and then
    return nameChanged;
}
baao
  • 71,625
  • 17
  • 143
  • 203
0

This line:

nameChanger(nameRaw, nameChanged);

needs to be something like:

nameChanged = nameChanger(nameRaw, nameChanged);

The reason why this is the case is due to Java being a pass by value. So you are being passed in the value of the String instead of its reference.

If you really, really want to be able to alter nameChanged; nameChanged would need to be a (typically mutable) Object with an appropriate setter/getter instead of a primitive. In this case, you would be pass by value 'A copy of the Object reference', which allows you to alter the contents of the Object within the method (if it's not immutable)

Shiraaz.M
  • 3,073
  • 2
  • 24
  • 40
0

private static String nameChanger(String nameRaw, String nameChanged) in this method, why are you passing nameChanged? I think nameChanged should be the value returned at the end of the nameChanger method.

I don't understand why you are checking if the nameChanged is null yet you initialized it as null and didn't change it.

String nameChanged = null;


if(nameChanged == null) {
        System.out.println("\nHere is the failed changed name: " + nameChanged);
        System.out.println("\nARE YOU KIDDING ME! WHY DOES THIS NOT WORK?!?! PLEASE HELP!!!!");
    } else {
        System.out.println("Here is the successfuly changed name: " + nameChanged);
        System.out.println("\nWhoever solved this problem is a god..");
    }

If you still go by your method, try nameChanged = nameChanger(nameRaw, nameChanged) instead of nameChanged = null

I hope this helps

Hanmaslah
  • 736
  • 1
  • 8
  • 14
0

Thank you to all of you who answered! Everything you've said helped me solve this!

My solution: nameChanged = nameChanger(nameRaw, nameChanged)

Thank you guys for the help I really appreciate your time and brain power to explain this to me and why!

Thanks and best regards, Aaron

Aaron Belz
  • 67
  • 7