【发布时间】:2015-08-09 14:36:47
【问题描述】:
我正在尝试使用 while 循环在我的简单程序中重新运行部分代码。在这个程序中,用户创建一个简单的帐户,输入验证码,然后登录。登录后,我希望允许用户退出,编辑他的个人资料设置等等。但是我有一个小问题。
假设用户刚刚编辑了他们的帐户设置。我希望他们能够返回“菜单”,而不是程序终止。
问题在于如何做到这一点。由于 java 中没有 goto 语句,根据我的阅读,我必须使用 while 循环。我不知道该怎么做。我只是无法绕过它。循环总是让我感到困惑。另外,我什至应该使用while 循环吗?使用for 或do-while 循环会更好吗?我应该使用什么表达方式?我需要break 声明吗?
我知道这不是一个具体的问题,但我们非常感谢任何能让我走上正确道路的帮助。
以下是完整代码供参考。
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println("To confirm you are not a robot, please enter this code: " + randm);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
【问题讨论】:
-
你有用java以外的其他语言写代码的经验吗?
标签: java while-loop goto