How is the String in a main method refer to someText in another method?

ppc :

I am trying to first output a String of like this:

Hello -

then I need that for example if I write, Jane it would output:

Hello - - Jane -

is this code correct? If not, what did I do wrong and what does this code actually do?

Thank you

public class myClass { 
   public static void main(String[] args) { 
     String a = new String("Hello"); 
     addHyphen(a); 
     System.out.println(a); 
} 


public static void addHyphen(String someText) { 
   someText = "-" + someText + "-"; 
   } 
}
BusyProgrammer :

If you want to print out a space, followed by a hyphen after the passed string in addHyphen(), then you can do something like this:

public static String addHyphen(String someText) { 
    return someText + " -"; 
}

Also, note that this function returns back a String, so you need to change your code in main():

String a = new String("Hello");  
System.out.println(addHyphen(a)); 

This simply returns the string back, with an appended hyphen to the calling function.

NOTE: If you want to enter the string as input, then you need to use the Scanner class. Code to get a String object input would be:

Scanner scan = new Scanner(System.in);
System.out.println(“Input a String:”);
String str = scan.nextLine();

Note that you need to import java.util.Scanner for using the Scanner class

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307242&siteId=1