Java编程银行帐户代码

时间:2013-12-14 00:26:10

标签: java

我正在使用eclipse查看我的代码,最常见的错误是“令牌上的语法错误,错位的构造”我不知道我做错了什么,但我是相当新的Java。

我的代码应该从银行帐户中提取指定的(用户输入)金额,我从10,000美元开始并设置程序,以便如果提款金额小于0或大于10,000美元,它将触发一个断言错误。

  class ThreadsUnitProject2 {
public static void main(Sting args [])
// Field member 
private int balance; 

public void BankAccount() 
{ 
balance = 10000; 
} 

public int withdraw(int amount) 
{   
// Subtract requested amount from balance 
balance-=amount; 

// Return requested amount 
return amount; 
} 


public int getBalance() 
{ 
return balance; 
} 


import java.util.Scanner; 

class BankAccountTester extends BankAccount
{ 
public static void main(String[] args) 
{ 
    Scanner scan = new Scanner(System.in); 

    BankAccount myAccount = new BankAccount(); 

    System.out.println("Balance = " + myAccount.getBalance()); 

    System.out.print("Enter amount to be withdrawn: "); 
int amount = scan.nextInt(); 

    assert (amount >= 0 && amount <= myAccount.getBalance()):"You can't withdraw that amount!"; 

    myAccount.withdraw(amount); 

    System.out.println("Balance = " + myAccount.getBalance()); 
} 

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

将您的类“ThreadsUnitProject2”重命名为BankAccount并从中删除main()方法并将BankAccountTester类设为public,最后从BankAccount构造函数中删除void

答案 1 :(得分:0)

在您的代码中看到如此多的问题后,我决定我应该修复它并让您尝试从下面的解决方案中学习。

这应该是第一个Class文件。

public class BankAccount {

    private int balance;

    public BankAccount() {      //constructor
        balance = 10000;
    }

    public int withdraw(int amount) {
        balance -= amount;
        return amount;
    }

    public int getBalance() {
        return balance;
    }
}

这应该是你的第二个Class文件。这个将包含您的main方法,该方法将测试您的BankAccount类。

import java.util.Scanner;

public class BankAccountTester {
    public static void main(String[] args) {
        Scanner     scan      = new Scanner(System.in);
        BankAccount myAccount = new BankAccount();

        System.out.println("Balance = " + myAccount.getBalance());
        System.out.print  ("Enter amount to be withdrawn: ");
        int amount = scan.nextInt();

        assert (amount >= 0 && amount <= myAccount.getBalance()) : "You can't withdraw that amount!";
        myAccount.withdraw(amount);

        System.out.println("NewBalance = " + myAccount.getBalance());
    }
}

请阅读并查看this link to proper coding conventions