简体   繁体   中英

Java How to prompt user input is incorrect java.lang.NullPointerException

I'm learning how to use a hashmap. I am trying to build an ATM program that can store the user's initial amount so that when I want to deposit or withdraw or check my balance. Below is my code.

import java.util.*;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Map<String, HashMap<String, String>> map = new HashMap<>();
        map.put("123456789", new HashMap<>());
        map.put("987654321", new HashMap<>());
        map.get("123456789").put("pin number" , "123456");
        map.get("123456789").put("phone number" , "0123456789");
        map.get("123456789").put("name" , "Thomas");
        map.get("123456789").put("balance" , "50000");

        boolean valid = false;
        Scanner in = new Scanner(System.in);
        while(!valid) {
            System.out.println("Enter Your Card Number");
            String card = in.next();
            System.out.println("Enter Your Pin Number");
            String pin = in.next();
            String actualPin = map.get(card).get("pin number");
            valid = pin.equals(actualPin);
            if (!valid) {
                System.out.println("Wrong Card Number or Pin Number");
                System.out.println("Try Again");
            } 
        }

    }
}

My question is how do I fix java.lang.NullPointerException issues? I entered my card number and pin correctly my above code will work but when I'm wrong then java.lang.NullPointerException. How do I prompt the user for the card and pin again?

Basically, you need to wrap the login process in a loop. For example

private Account login() {
  Account account = null;
  while (null == account) {
    String cardNumber = promptForString("Enter card number: ");
    String pin = promptForString(in, "Enter pin: ");
    account = findAccount(in, cardNumber, pin);
  }
  return account;
}

/**
 * Emit the prompt and read in a String response from the Scanner
 */
private String promptForString(Scanner in, String prompt) { ... }

/**
 * Find the Account matching the card/pin provided.  Returns null if the
 * credentials do not match an Account
 */
private Account findAccount(String cardNumber, String pin) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM