我創建了一個小片段來說明我的問題。如果我要輸入其中一個用戶名,第一個檢查就可以確定用戶已經存在。但第二個輸入可以繞過檢查。我該怎麼做才能確保沒有人能繞過它?檢查散列表中是否已經存在一個值,並允許用戶輸入有效值(如果有)
public static void main(String[] args) {
HashMap<String, String> uID = new HashMap<>();
Scanner scan = new Scanner(System.in);
String input = null;
uID.put("James", "25");
uID.put("Jack", "25");
uID.put("John", "25");
System.out.println("Enter your username and age");
input = scan.nextLine();
if (uID.containsKey(input)) {
System.out.println("Username already exist, choose another username.");
input = scan.nextLine();
uID.put(input, "25");
}
}
使用while循環,而不是'if' –
如果用戶按照您的指示,那麼它永遠不會起作用,因爲'詹姆斯25'的(用戶名**和**的年齡,像你說的輸入)輸入時, 'input'的值將是'「James 25」',並且這不是地圖中的*鍵*。 – Andreas
但是,積極的一點是,無論你說自己多大年紀,計算機都會認爲你是25歲。我的妻子喜歡這個想法。 – ajb