Home > database >  change string content in another method in java
change string content in another method in java

Time:12-27

I'm trying to write simple code when user write his name in another method than it display his name the problem that is string name keep staying null and it doesn't change

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        String name="";
        saisir(name);
        System.out.println("your name is " name);
}
    static String saisir (String title){
        Scanner s=new Scanner(System.in);
        System.out.println("write your name");
        String name = s.nextLine();
        return name;
    }

}

CodePudding user response:

In Java, methods are passed by value, which means the String you sent as a parameter won't be affected by the changes inside the method (although you didn't actually change it :P) . It uses a copy of it. If you want the changed name you should make the assignment in the main() method like other answers are suggested.

name = saisir();

Since you also don't need the parameter there.

CodePudding user response:

Code this:

name = saisir(name);

Or better:

name = saisir();

and delete the title parameter since you don’t use it.

CodePudding user response:

You are returning the name, but not keeping it. You are passing a title, but not using it. Let's fix both of those. Like,

public static void main(String[] args) {
    String name = saisir();
    System.out.println("your name is " name);
}
static String saisir() {
    Scanner s=new Scanner(System.in);
    System.out.println("write your name");
    return s.nextLine();
}

CodePudding user response:

try it like this

public class Main {
    public static void main(String[] args) {
        String name = "";
        name = saisir(); //set "name" equal to the String returned by saisir()
        System.out.println("your name is "   name);
    }

    static String saisir() { //there is no need for this method to take any parameters
        Scanner s = new Scanner(System.in);
        System.out.println("write your name");
        String name = s.nextLine();
        return name;
    }
}
  • Related