好奇为什么while循环只打印最后一个项目?

时间:2019-04-14 19:42:38

标签: java

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

调试代码时,我注意到当我在第20行中使用system.out.print时,输出的项目只是文本文件中的最后一项。我知道使用println可以解决此问题,但是我想知道是什么原因导致的?只是为了扩展我的知识。

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

jon:123432luis:358273frogboy156:32423false

但是我得到了这个

frogboy15632423false

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

1 个答案:

答案 0 :(得分:1)

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

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

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