首页 > 解决方案 > 变量已在范围内定义

问题描述

我只是想说我是 Java 新手,我一直在练习并获得了一点点更好。我正在尝试制作一个非常简单的银行系统,您可以在其中创建帐户、存款和取款。不过,我现在有点卡住了,希望有人能帮助我。

我试图从用户那里获取输入,然后在参数中使用用户输入创建一个新的对象实例,它给了我和错误。这是它给我错误的代码行,谢谢!

它在 userName String 变量的 bankAccount 对象创建行上提示我错误。

case 1:
                System.out.println("Please Enter Your Name: ");
                String userName = input.nextLine();
                System.out.println("Please Enter a 4 digit pin number: ");
                int pinNumber = input.nextInt();
                int accountNumber = rand.nextInt(5100 - 1100) + 1000;
                System.out.println("Account Created with the following credentials:\n " +
                        "Name: " + userName + "\n" +
                        "Account Number: " + accountNumber + "\n" +
                        "Pin Number: " + pinNumber);
                bankAccount userName = new bankAccount(userName, accountNumber);
                break;

标签: java

解决方案


With java, you cannot make a local variable with the same name, even though the data types are different.

userName is already used as a String variable so you cannot make a new bankAccount named userName. You could name it userAccount though.

Example:

 bankAccount userAccount = new bankAccount(userName, accountNumber);

You could then add this to an array or Map to reference that particular userAccount later.

bankAccount[] accounts = new bankAccount[];
//several lines of code
bankAccount[0] = userAccount;

or

Map<String, bankAccount> bankAccount accounts = new HashMap<String, bankAcount>();
//several lines of code
bankAccount.put(userAccount.userName, userAccount);

To retrieve the userAccount of a certain user, you can do this later in the program.

bankAccount userAccount = bankAccount.get("bob");

This is get the bankAccount that has "bob" as the userName.

I imagine you're doing this as an independent project. If you have the time, it could be a good idea to learn some java from codecademy to get a better understanding of the basics.


推荐阅读