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

How to avoid duplicate outputs in java text files?

伙计们,我有一个简单的问题。

我在 java.

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

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

Hamada 114455
Ahmed  236974145
Johny  4123745

这些记录的编程格式是这样的:

String username, int password

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

username: Ahmed
password: 114455

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

如果不是它说 "Wrong username or pasword"

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

这是我的代码:

                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 !!");
 boolean bool = false;
Scanner y = null;
try{
y = new Scanner(new File("Path"));
while(y.hasNext())
{
String a = y.next();
int b = y.nextInt();
if((a == null ? user2 == null : a.equals(user2)) && b == pass2)
    bool = true;
}
if(bool) 
    System.out.println("Welcome :)");
else 
    System.out.println("Wrong username or password .. try again !!");
}

在您的情况下,您正在检查文本文件中每个条目的 if else 条件。您还可以在控制台上显示每个条目的消息。我修改了程序并在退出循环后写入控制台。

这样修改你的代码:

boolean isWrong = true ;
while(y.hasNext())
{
    String a = y.next();
    int b = y.nextInt();
    if((a == null ? user2 == null : a.equals(user2)) && b == pass2)
        isWrong = false ;
}
if(isWrong) 
    System.out.println("Wrong username or password .. try again !!");
else
    System.out.println("Welcome :)");