java - 好奇为什么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
解决方案
文本文件中的行以 \r\n 结尾。\n 用作分隔符。所以这意味着每个密码都以 \r 结尾,因此所有内容都打印在同一行。见https://stackoverflow.com/a/32697185/1095383
对于第一次迭代,您的变量如下。
String tempUsername = "jon";
String tempPassword = "123432\r";
推荐阅读
- r - R flexdashboard 上的多语言支持
- php - 令牌在google api php中过期
- java - 如何从地图集合中获取 Pojos 列表
- python - 如何通过 Twisted 的 Web 服务器正确地为 Django 应用程序提供服务?
- javascript - 如何遍历车把中的对象数组
- javascript - 当我添加花括号以便能够向上下文添加更多元素时,如何访问 GraphqlServer 上下文对象?
- google-cloud-platform - 从 Google GCP 项目凭据 API 密钥中检索信息
- xml - 使用 xslt 2.0 将 xml 日期时间数据转换为 yyyy-MM-dd hh:mm:ss:ff
- stream - WebFlux - 如何使用 Flux
作为列表 服务方法中的参数 - android - 我无法从华为 p40 系列设备获取 Firebase 令牌