简体   繁体   中英

I want to pass three different strings to my main method in java. How do I do this?

I want people to enter there first name then middle name then last name inside of a method. I then want to pass all three variables into my main method.

Is there anyway I can do this?

And how would I get the different data stored in my main method?

No there isn't but use Command line arguments.

public class YourProgram
{
   public static void main(String []args)
    {

    }
}

c:\>java YourProgram "First String" "Second String" "Third String"

If by main you refer to application's entry point, the main method. Eg

public class SomeClass{
    public static void main(String[] args){
         String firstName = args[0];
         String middleName = args[1];
         String lastName = args[2];
    }
}

Then you can pass it as a three arguments after program name when you call it. java SomeClass "first name" "middle name" "last name"

If you're referring to the actual main method, as in the first method that runs, you can't pass in any variables because there isn't a place to pass a variable, it's where the program starts.

edit: as AVD said, you can pass the variables if you run the program from the console, but not inside the code itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM