我试图这样做,如果用户名和/或密码不正确,程序将重新运行它,而不是只在else语句中执行print命令。我尝试在else语句中添加另一个while循环并将if语句嵌套在其中检查其中的用户名和密码,但后来我意识到我必须将if语句中的所有代码复制到else语句中,这显然似乎喜欢它不是正确的解决方案,可能非常笨重。什么是从一开始就将程序引回运行的正确方法?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
答案 0 :(得分:1)
考虑以下逻辑
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
如果command
等于calculator
,那么它如何等于renameUser
你应该拥有它
if (....) {
}
else if (...) {
}
语句或作为switch语句
答案 1 :(得分:0)
这里的代码片段正在增加你软件的cyclomatic complexity,这使得很难做出决定,如果你想稍后改变它,你有更多的机会打破代码而不是成功
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
尝试设计更像巫婆逻辑的东西
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}