我正在尝试编写一个简单的程序,用户在命令行输入用户名和密码。程序检查用户输入是否有效,如果是,则显示欢迎,无论名称是什么。程序还检查密码是否有效。我无法找到在main中调用checkCommandLine并将用户输入传递给它的方法。有什么建议吗?
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
}
}
答案 0 :(得分:1)
在main方法中,您可以传递命令行参数,如下所示:
public static void main (String[]args){
checkCommandLine(args);
....
}
要传递命令行参数,可以参考http://www.javatpoint.com/command-line-argument
答案 1 :(得分:0)
你可以像Agrawal一样传递main方法的参数。
如果是这样,您可以从cmd执行它,如下所示
java HelloWorld3 yourID abc123
否则使用Scanner在代码中获取输入