用java写循环登录系统我的要求是:使用while循环确定登录还是退出再使用while循环输入账号和密码正确之后进入选择界面利用if else实现选择
界面,选择完后输出相应的结果,再回到登录或退出界面。
以下是示例代码:
import java.util.Scanner;
public class LoginSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String username, password;
while (true) {
System.out.println("请选择:1.登录 2.退出");
int choice = scanner.nextInt();
if (choice == 1) {
boolean loginSuccess = false;
while (!loginSuccess) {
System.out.print("请输入用户名:");
username = scanner.next();
System.out.print("请输入密码:");
password = scanner.next();
if ("admin".equals(username) && "123456".equals(password)) {
System.out.println("登录成功!");
loginSuccess = true;
} else {
System.out.println("用户名或密码错误,请重新输入!");
}
}
while (loginSuccess) {
System.out.println("请选择:1.查询余额 2.转账 3.退出");
int choice2 = scanner.nextInt();
if (choice2 == 1) {
System.out.println("您的余额为1000元。");
} else if (choice2 == 2) {
System.out.println("请输入转账金额:");
double amount = scanner.nextDouble();
System.out.println("转账成功,已转出" + amount + "元。");
} else if (choice2 == 3) {
System.out.println("退出成功!");
loginSuccess = false;
} else {
System.out.println("输入有误,请重新选择!");
}
}
} else if (choice == 2) {
System.out.println("退出成功!");
break;
} else {
System.out.println("输入有误,请重新选择!");
}
}
}
}
注:此为简化版代码,实际使用中需要做更多的输入校验和异常处理。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/bPvt 著作权归作者所有。请勿转载和采集!