我是 Java 新手,我想我会制作经典的用户名和密码验证程序之一,我已经成功地制作了没有明显错误的程序,但是如果用户输入了不正确的信息,我希望程序基本上重新启动输入. 每次用户输入错误信息时,我将如何成功重新启动程序?
代码如下:
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
}
}
}
我知道这是非常基本的,因为我说我对 Java 很陌生(2 小时前是新的)。
我想在 else 条件语句中调用“main”方法,但是我听说比程序第一次启动时使用“main”方法的次数更多是基本做法。
提前致谢 :)
我希望这就是你想要的。
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
boolean isValidUser = false;
while(!isValidUser) {
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!");
isValidUser = true;
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct");
isValidUser = false;
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句