在我的do while循环中,主体最初运行良好,但是在循环时,它会像应有的那样打印前两个语句,但是它不允许我输入名称,而是直接输入pin,而我输入的内容都会跳过休息,问我是否要另一笔交易。

我有部分提交的数组对象。对象中的变量是名称,密码,帐号和余额。添加新对象并设置余额时,输入的新余额也会导致以前对象的余额发生变化。我认为这与将余额变量声明为静态有关,但是我没有使其成为静态,因此我会出现错误“无法对CustomerRecord类型的非静态方法withdraw(double)进行静态引用”。 (已解决)谢谢。

public class BankCustomers
{
public static void main(String[] args)

    //------------------------------------------------
    //Part4: Find a customer record from anotherArray
    //to do transaction(s) and update the record's balance

    char repeat; // User control to repeat or quit
    Scanner keyboard = new Scanner(System.in); //creating the scanner

    String aName;
    int aPin;
    double aWithdraw;
    double aDeposit;

    do{


        //Read customer information before search
        System.out.println();
        System.out.println("Lets make a transaction");
        System.out.println("Enter customer full name");
        aName = keyboard.nextLine( );

        System.out.println("Enter Pin");
        aPin = keyboard.nextInt();


        //Search an Array for equal aName and aPin
        for (int i = 0; i < index; i++)
        {
            CustomerRecord cRecord = anotherArray[i];
                if((cRecord.getName().equalsIgnoreCase(aName)) && (cRecord.getPin()           ==(aPin)))
                {
                    System.out.println(cRecord);

                    System.out.println("Enter Withdraw Amount");
                    aWithdraw = keyboard.nextDouble();
                    CustomerRecord.withdraw(aWithdraw);

                    System.out.println("Enter Deposite Amount");
                    aDeposit = keyboard.nextDouble();
                    CustomerRecord.deposit(aDeposit);
                    System.out.println(cRecord);
                }
        }


        System.out.println("\nAnother Transaction? (y for yes)");
        repeat = keyboard.next().charAt(0);

    }while(repeat == 'y' || repeat == 'Y');

        //Print the records on screen
    for (int i = 0; i < index; i++)
        System.out.print(anotherArray[i]);

    }

最佳答案

您的问题是双重的:

首先,balance istatic,这意味着它与类相关联,而不与任何实例(对象)相关联,或者换句话说,它与该类的所有实例共享。

其次,正如您指出的那样,您的静态方法withdraw正在访问balance。关于静态的考虑同样适用于此-该方法与类相关联,并且不能访问非静态的成员。

要解决第二个问题,请从withdraw声明中删除static(并从balance中也删除static。这将使您的代码CustomerRecord.withdraw()无法编译,因为withdraw现在与该类本身无关,但是因此,您需要使用一个实例并在该实例上调用withdraw

cRecord.withdraw(aWithdraw);


对于deposit同样

10-01 02:20