简体   繁体   中英

Is it possible to use a scanner this way?

Ok so, this is whats going on. I'm making a simple simple bank program .

This is what I want to do, notice the variables for my Account class (a1, a2, a3)

This works perfectly fine, but not for what I want to do. In the switch cases, I want to be able to let the user input the name under the account and be able to edit it.

Now, I know if I were to basically do this:

Account AccountObject = new Account ();
balance.put (sc.nextLine(), AO.addFunds)

Then I would have separate users, but the funds would essentially all be the same. How would I make them separate*

I know once I figure out how to do this, I'll be set to move on to more complicated projects.

import java.util.Hashtable;
import java.util.Scanner;

class Data {

    public static void main(String args[]) {
        Hashtable<String, Double> balance = new Hashtable<String, Double>();
        Scanner sc = new Scanner(System.in);
        Scanner sa = new Scanner(System.in);

        boolean quit = false;
        boolean quit2 = false;

        // Create account variables
        Account a1 = new Account();
        Account a2 = new Account();
        Account a3 = new Account();
        Account a4 = new Account();
        Account a5 = new Account();

        // Add funds to variables in Hashtable
        balance.put(sc.nextLine(), a1.addFunds());
        balance.put(sc.nextLine(), a2.addFunds());
        balance.put(sc.nextLine(), a3.addFunds());
        balance.put(sc.nextLine(), a4.addFunds());
        balance.put(sc.nextLine(), a5.addFunds());

        do {
            System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
            int input = sa.nextInt();
            switch (input) {
                case 1:
                    System.out.println(balance.get(sc.nextLine()));
                    break;
                case 2:
                    System.out.println(balance.put(sc.nextLine(), a1.addFunds()));
                    break;
                case 3:
                    System.out.println(balance.put(sc.nextLine(), a1.withdrawFunds(sa.nextDouble())));
                    break;
                case 4:
                    quit = true;
                    break;
            }
        } while(!quit);
        System.out.println("Exiting menu");
    }
}

Account class

import java.util.Scanner;

public class Account {

    int balance;
    String name;

    public double addFunds() {
        Scanner sa = new Scanner(System.in);
        double amount = sa.nextDouble();
        balance += amount;
        return balance;
    }

    public String Acct(String names) {
        Scanner sc = new Scanner(System.in);
        name = names;
        return name;
    }

    public double withdrawFunds(double amount) {
        balance -= amount;
        return balance;
    }

    public String toString() {
        return String.format("Balance: %n", balance);
    }
}

You should create an Account class, which is model for an account. I suggest you do not handle the user input inside the Account class.

Account class

public class Account {

    private String name;
    private int balance;

    public Account(String name, int startBalance) {
        this.name = name;
        this.balance = startBalance;
    }

    public void addFunds(int amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("Amount must be absolute");
        }
        this.balance += amount;
    }

    public void withdrawFunds(int amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("Amount must be absolute");
        }
        else if (amount > this.balance) {
            throw new IllegalArgumentException("You don't have that, so you cannot grab that.");
        }
        this.balance -= amount;
    }

    public String getName() {
        this.name;
    }

    public int getBalance() {
        return this.balance;
    }
}

Now, if you want, you can create some accounts and add them to an ArrayList<Account> . I do not know why you would use a HashMap : if you have just a list with all Account objects, you have all information you need.

ArrayList<Account> accounts = new ArrayList<Account>();
Scanner sc = new Scanner(System.in);

You can implement your user input like something like:

private static ArrayList<Account> accounts = new ArrayList<Account>();
private static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    initializeSomeBankAccounts();
    displayUI();
}

private static void initializeSomeBankAccounts() {
    for (int i = 0; i < 2; i++) {
        System.out.print("Insert " + (i > 0 ? "another " : "") + "account name: ");
        String name = sc.nextLine();
        System.out.print("Insert start balance: ");
        int startBalance = sc.nextInt();
        sc.nextLine();

        // Create a new account using the user input
        Account account = new Account(name, startBalance);
        // Add the account to our list with accounts.
        accounts.add(account);
    }
}

public static void displayUI() {
    boolean quit = false;
    while (!quit) {
        // Show a menu with the available actions
        System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");

        int action = sc.nextInt();
        sc.nextLine();


        Account account;
        // Since we ask the user to insert a right account name, we can
        // guarantee that the variable 'account' contains an Account
        // object.
        switch (action) {
            case 1:
                account = askAccount();
                System.out.println(account.getBalance());
                break;
            case 2:
                account = askAccount();
                System.out.print("Amount: ");
                int amount = sc.nextInt();
                account.addFunds(amount);
                break;
            case 3:
                account = askAccount();
                System.out.print("Amount: ");
                amount = sc.nextInt();
                account.withdrawFunds(amount);
                break;
            case 4:
                quit = true;
                break;
        }
    }
}

private static Account askAccount() {
    System.out.println("Which account? ");

    Account account = null;
    boolean accountFound = false;

    // Now the user has to input a valid account name, we're going to
    // search for that account name in the list. If it is found, we
    // have the whole Account object stored into the variable 'account'.
    // Otherwise, if it is not found, then we repeat to ask to insert
    // an account name, until a account name is given which is present
    // in our list.
    while (!accountFound) {
        String accountName = sc.nextLine();
        account = searchAccount(accountName);
        if (account == null) {
            System.out.println("Account not found. Insert another account:");
        }
        else {
            accountFound = true;
        }
    }
    return account;
}

/**
 * Searches an account from our list of all accounts.
 *
 * @param name The name to search for.
 * @return The account if found, or null otherwise.
 */
private static Account searchAccount(String name) {
    for (Account account : accounts) {
        if (account.getName().equals(name)) {
            return account;
        }
    }
    return null;
}

I also got a few suggestions:

  • You have some variables which are not used, ie quit2 . You might want to remove them.
  • As far as I know, you do not need to have two Scanner s; one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner.
  • You have variables starting with an uppercase character, ie AccountObject . In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter.
  • You are using the class Hashtable , but it is recommended to use HashMap<Key, Value> .

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