简体   繁体   English

这样可以使用扫描仪吗?

[英]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) 这就是我想要做的,请注意我的Account类的变量(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. 您应该创建一个Account类,该类是一个帐户模型。 I suggest you do not handle the user input inside the Account class. 我建议您不要处理Account类中的用户输入。

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> . 现在,如果需要,您可以创建一些帐户并将其添加到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. 我不知道为什么要使用HashMap :如果仅包含所有Account对象的列表,则您将拥有所需的所有信息。

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 . 您有一些未使用的变量,即quit2 You might want to remove them. 您可能要删除它们。
  • As far as I know, you do not need to have two Scanner s; 据我所知,您不需要两个Scanner one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner. 一个就足够了,因为您可以在同一扫描仪上同时调用nextLine()nextInt()
  • You have variables starting with an uppercase character, ie AccountObject . 您具有以大写字符开头的变量,即AccountObject In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter. 在Java中是允许的,但是Java命名约定规定,应以小写字母开头的变量。
  • You are using the class Hashtable , but it is recommended to use HashMap<Key, Value> . 您正在使用Hashtable类,但建议使用HashMap<Key, Value>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 可以通过这种方式使用扫描仪吗? - It is possible to use a Scanner in this manner? 是否可以使用扫描仪输入不同对象的值? - Is it possible to use a Scanner to input values for different objects? 有没有办法使用扫描仪来设置数组中的维数? - is there a way to use a Scanner to set the number of dimensions in an array? 是否可以多次使用文件扫描程序而不声明多个扫描程序? - Is It Possible to Use a File Scanner Multiple Times Without Declaring Multiple Scanners? 是否可以在 main 方法之外使用 Scanner 并仍然调用它? - Is it possible to use the Scanner outside the main method and still call it in? 关于可以重新使用Java Scanner的简单问题? - Simple issue about possible to re use java Scanner? 在带try / catch的开关状态中使用扫描器和随机的正确方法 - A right way to use Scanner and Random in Switch-statement with Try/catch 有什么办法可以在不同的类中使用 Scanner 对象吗? - Is there any way I can use a Scanner object in a different class? 有没有办法使用Scanner对象在文本文档中搜索特定数据? - Is there a way to use a Scanner object to search a text document for specific data? 如何使用扫描仪以正确的方式读取文件中的重音字符? - How to use scanner to read accented characters from file in correct way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM