Aysegul Altug
Aysegul Altug

Reputation: 1

can't pass user input to main in method call

I am trying to write a simple program where user enters username and password at the command line. Program check user input if valid if yes, it displays Welcome whatever the name is. Program also check password valid. I couldn't find a way to call checkCommandLine in main and pass user input to it. Any advise?

public class HelloWorld3 {

    public static boolean checkCommandLine(String [] args){
    if (args.length == 1)
        {
            //If the string is blank “  “ then display error message
            if (args[0].trim().isEmpty())
            {
                System.out.println("args[0] is null");
                return false;
            }
            return true;
        }
        //If args does not contain a string then display an error message 
        else if (args.length == 0)
        {
            System.out.println("args[0] doesn't contain string");
            return false;
        }
        return true;
    }

    public static final String Password = "abc123";

    public static boolean checkPassword(String uPassword){
        if (uPassword.equals(Password)){
            return true;
        } else {
            System.out.println("Password invalid");
            return false;
        }
    }

    public static void main (String[]args){
    //to receive the command line arguments
    //call checkCommandLine
    //if all ok the say welcome username
    if (checkCommandLine(new String[] {"A", "B"})){
        System.out.println("Welcome" + " " + "A");
    }
    //call checkPassword

    //if valid then say from within main, your password is good
    if (checkPassword("abc123")){
        System.out.println("Your password is good");
    }
    //if not ok, then say password invalid  
    }
}

Upvotes: 0

Views: 231

Answers (2)

Hyun I Kim
Hyun I Kim

Reputation: 589

You can pass the args of main method just like Agrawal did.

If so, you can execute it from cmd as follows

java HelloWorld3 yourID abc123

else use Scanner to get the input during your code

Upvotes: 0

Loki
Loki

Reputation: 801

In the main method you can pass the command line arguments like this:

public static void main (String[]args){
    checkCommandLine(args);
    ....
}

For passing the command line arguments you can refer http://www.javatpoint.com/command-line-argument

Upvotes: 1

Related Questions