gpt4 book ai didi

java - 如何根据 HashMap 的键和值检查两个输入?

转载 作者:行者123 更新时间:2023-12-01 09:10:37 24 4
gpt4 key购买 nike

我刚刚学习 HashMap,并且刚刚使用它们编写了我的第一个程序。由于某种原因,我检查输入的输入是否与键匹配及其相应的值总是返回 false。谁能告诉我这是为什么?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;

public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();

File file = new File(filename);
Scanner inputFile = new Scanner(file);

while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}

inputFile.close();

//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}

最佳答案

while 循环内的代码存在两个问题,如下所述:

(1) keyboard.next() 正在读取控制台输出文本,即读取打印文本“密码”,因此将 keyboard.next() 替换为 keyboard.nextLine();

(2) 您没有处理 tries 计数的 else 条件

您可以引用以下带内嵌注释的代码:

while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}

关于java - 如何根据 HashMap 的键和值检查两个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942044/

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