java - 变量已在范围内定义
问题描述
我只是想说我是 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;
解决方案
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.
推荐阅读
- python - 如何从 configparser 文件加载所有变量?
- python - Python使用selenium webdriver获取元素的CSS颜色值
- c++ - 我可以从基类调用派生类构造函数吗?
- r - 子集 data.table 以按组获取持续时间内最近的 3 行或更多行
- excel - 强制 Excel 更新计算
- c++ - CListCtrl 类不推荐使用的函数 - 可以使用哪些替代函数
- j - 使用#(复制)作为二维数组的选择或过滤器
- android - 我们可以使用外部支付处理器还是必须在 Google Playstore 中使用应用内结算?
- mysql - 即使在使用 --skip-grant-tables 启动 mysql 服务器后也会出错
- java - 了解 Java 的集合和可变对象 - 大小、负载因子和阈值