gpt4 book ai didi

java - 如何避免java文本文件中的重复输出?

转载 作者:行者123 更新时间:2023-12-01 22:02:42 24 4
gpt4 key购买 nike

我有一个简单的问题。

我使用java中的文本文件创建了一个简单的登录系统。

我的文本文件有这样的记录:

Hamada 114455
Ahmed 236974145
Johny 4123745

这些记录的编程格式如下:

String username, int password

问题出在登录操作上,系统应该这样工作:

username: Ahmed
password: 114455

系统应在文本文件中搜索用户名和密码,如果存在则显示“欢迎:)”。

如果不是,则显示“用户名或密码错误”

问题:如果我输入错误的用户名或密码,那么它会为未找到用户名和密码的每一行写入错误的用户名或密码。

这是我的代码:

                System.out.println("Login Page");
System.out.printf("Username: ");
String user2 = input.next();
System.out.printf("Password: ");
int pass2 = input.nextInt();
Scanner y = null;
try{
y = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt"));
while(y.hasNext())
{
String a = y.next();
int b = y.nextInt();
if((a == null ? user2 == null : a.equals(user2)) && b == pass2)
System.out.println("Welcome :)");
else
System.out.println("Wrong username or password .. try again !!");
}
}
catch(Exception e)
{
}

最佳答案

while 循环中,使用 boolean 变量(初始化为 false)。如果找到具有相同数据的条目,请将其设置为 true

然后在 while 循环之外打印结果。

boolean userExists = false;
while (y.hasNext()) {
// .....
if((a == null ? user2 == null : a.equals(user2)) && b == pass2)
userExists = true;

// ...
}

if (userExists)
System.out.println("Welcome");
else
System.out.println("Wrong username or password .. try again !!");

关于java - 如何避免java文本文件中的重复输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com