首页 > 解决方案 > 好奇为什么while循环只打印最后一项?

问题描述

我创建了一个在文本文件中验证用户名和密码的类

在调试我的代码时,我注意到当我在第 20 行使用 system.out.print 时,输出的项目只是我的文本文件中的最后一个项目。我知道使用 println 会修复它,但我想知道是什么原因造成的?只是为了扩展我的知识。

我以为这是应该打印出来的

jon:123432luis:358273frogboy156:32423false

但我得到了这个

青蛙男孩15632423假

班级

mport java.io.File;
import java.util.Scanner;

public class verificaiton {


    public static void verifyLogin(String username, String password) {
        boolean found = false;
        String tempUsername = "";
        String tempPassword = "";
        try {

            Scanner x = new Scanner(new File("src/info.txt"));
            x.useDelimiter("[:\n]");

            while (x.hasNext() && !found) {

                tempUsername = x.next();
                tempPassword = x.next();
                System.out.print(tempUsername + tempPassword + "");
                if (tempUsername.trim().equals(username) && tempPassword.trim().equals(password.trim())) {
                    found = true;
                }

            }
            x.close();
            System.out.println(found);
        }
        catch(Exception e){
            System.out.println("Error");
        }
    }
}

主要的

public class main {
    public static void main(String[] args){
    verificaiton check = new verificaiton();
    check.verifyLogin("Luis", "32534");

}}

文本文件

jon:123432
luis:358273
frogboy156:32423

标签: java

解决方案


文本文件中的行以 \r\n 结尾。\n 用作分隔符。所以这意味着每个密码都以 \r 结尾,因此所有内容都打印在同一行。见https://stackoverflow.com/a/32697185/1095383

对于第一次迭代,您的变量如下。

String tempUsername = "jon";
String tempPassword = "123432\r";

推荐阅读