这是我的代码的一部分(后面有一个 BankAccount 类):
import java.util.Scanner; //This library is added
public class BankSystem_
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);//Scanner object to read input
BankAccount ba = null;
//Define variables
int task=0;
int accountNumber=0;
String accountName="unknown";
double balance=0;
double interestRate=.05;
do
{
System.out.println("1.\t Open new account");
System.out.println("2.\t Current Balance");
System.out.println("3.\t Deposit");
System.out.println("4.\t Withdrawal");
System.out.println("5.\t Change Interest Rate");
System.out.println("6.\t Bank Statement");
System.out.println("7.\t Exit");
System.out.println("Please create an account and choose a task: ");
task=keyboard.nextInt();
switch (task)
{
case 1:
System.out.print("What is the account name?: ");
accountName=keyboard.nextLine();
System.out.print("\nWhat is the account number?: ");
accountNumber=keyboard.nextInt();
System.out.print("\nAmount of money to start your account?: ");
balance=keyboard.nextDouble();
while (balance < 100)
{
System.out.println("The minimum amount to open a new account should be $100");
System.out.print("Amount of money to start your account?: ");
balance=keyboard.nextDouble();
}
BankAccount ba = new BankAccount(accountName,accountNumber,balance,interestRate);
System.out.print(ba.NewAccount());
break;
case 2:
if (ba != null)
{
System.out.print(ba.Balance());
}
break;
case 3:
if (ba != null)
{
System.out.print(ba.Deposit());
}
break;
case 4:
if (ba != null)
{
System.out.print(ba.Withdrawal());
}
break;
case 5:
if (ba != null)
{
System.out.print(ba.ChangeInterestRate());
}
break;
case 6:
if (ba != null)
{
System.out.print(ba.BankStatement());
}
break;
case 7:
System.exit(0);
break;
}
}while(task >=1 && task <=7);
}
}
*代码的目的是在选择任务1之前警告选择任务2-6的用户。所以,我必须检查BankAccount的对象是否不为空才能继续。
每当我包括:
BankAccount ba = null;
我稍后在代码中包含:
BankAccount ba = new BankAccount(accountName,accountNumber,balance,interestRate);
声明对象,编译器告诉我variable ba is already defined in method main(String[])
但是当我删除空值时,编译器告诉我:
variable ba might not have been initialized
if (ba != null)
我这里有什么问题吗?