JavaOOP编程练习(涉及文件读取及异常处理)

// This article is part of Exercise 4 for XJCO1721 of SWJTU-Joint School
// which follows the book "Introduction to Java Programming, Brief Version,Tenth Edition."
// by Y. Daniel Liang, Armstrong Atlantic State University.

// Written by Hao Shi

题目描述:

第一部分

Create a file named Ex7.java, containing anon-public class BankAccount. This represents a bank account by an account ID,the name of the account holder and its current balance. These fields and thevarious methods that you must implement are shown in the following UML diagram.

The first of the two constructors shouldinitialise the balance field to 0.

The deposit method should checkthe provided amount. If the amount is greater than 0, it should add that amountto balance and return true; otherwise, it should leave thebalance untouched and return false.

The withdraw method should alsocheck the provided amount. If the amount is greater thanzero and less than or equal to the current balance, it shouldsubtract that amount from the balance and return true; otherwise, itshould return false.

Add to Ex7.java a public classnamed Ex7, containing a small program that teststhe BankAccount class. It should createa BankAccount object with an ID and name of your choosing and ainitial balance of £20,000. It should use the withdraw method towithdraw £2,500 and the deposit method to deposit £4,000. It shouldthen print the current balance of the account.

(Loosely based on Liang exercise 9.7,p.361)

第二部分

Copy Ex7.java from Set 3 to anew file, Ex9.java. Remember to also change the name of the classcontaining the main program to Ex9.

Replace the contents ofthe main method in Ex9 with a new program that

Creates a list capable ofholding BankAccount objects

Reads IDs, account holder names andinitial balances from a file

Uses each name and balance to createa BankAccount object

Adds each BankAccount object tothe list

The data file used by the program shouldhave lines that look like this:

    1,JohnSmith,100

    2,Sarah Davies,350

    ...

The simplest approach is probably to readeach line as a string and then call its split method to split it oncommas - see the API documentation forfurther details.

解题过程:

首先创建第一部分中要求的类

class NewBankAccount {
	int id;
	
	String name = new String();
	
	int balance;
	
	NewBankAccount(int id, String name){
		this.id = id;//"this"的使用是为了区别同名的类中的变量和方法中的变量。this代表的是类中的变量。
		this.name = name;
		balance = 0;
	}
	//构造器可以重载
	NewBankAccount(int id, String name, int balance){
		this.id = id;
		this.name = name;
		this.balance = balance;
	}
	
	int getId() {
		return id;
	}
	
	String getName() {
		return name;
	}
	
	int getBalance() {
		return balance;
	}
	
	boolean deposit(int amount) {
		if (amount > 0) {
			balance = balance + amount;
			return true;
		} else {
			return false;
		}
	}
	
	boolean withdraw(int amount) {
		if ((amount > 0) && (amount <= balance)) {
			balance = balance - amount;
			return true;
		} else {
			return false;
		}
	}
}

开始写主程序

public class Ex9 {

	public static void main(String[] args) throws FileNotFoundException {
		

throws 是为了抛出一个异常,在我使用的IDE(eclipse)中,有的情况下会强制软件编程者处理异常。就比如下面我在打开一个文件是必须要检测是否有”fileNotFoundException“异常。在具体遇到代码时需要用try-catch来处理异常。对于throw和throws的用法,这位博主@wylovedx有非常精彩详细的讲解,贴下链接https://blog.csdn.net/wy5612087/article/details/47861077

创建list

		NewBankAccount[] list = new NewBankAccount[100];

对于list的创建,可以是任何类,包括程序的基础类和程序员自建的类,基本语法是

className[ ] listname = new className[listSize];

两个例子

double[ ] myList1 = new double[10];

MyselfClass[ ] myList2 = new MyselfClass[10];

打开文件

                /*java.io.File file = new java.io.File("BankAccount.txt");
		 *Scanner input = new Scanner(file);
		 *这一段代码理论上的作用与下一行相同,但在实际运行中会从文档的第二行开始读取,暂时不知道错误在哪里。
		 */
		Scanner input = new Scanner(new java.io.File("BankAccount.txt"));

读取文件

		while (input.hasNext()) {
			
			String line = input.nextLine();
			
			int i = 0;
			int id = 0;
			String name = null;
			int balance = 0;
			
			for (String retval: line.split(",")){
				
	                    if (i == 0) {
	                	id = Integer.valueOf(retval);
	                    }else if(i == 1) {
	                	name = retval;
	                    }else if(i == 2) {
	                	balance = Integer.valueOf(retval);
	                    }
	            
	                i = i + 1;
	                }
					
			list[id] = new NewBankAccount(id, name, balance);
			
			System.out.println("The current balance of "+list[id].getName()+" is "+list[id].getBalance());
		}

打开文件的部分有很多,我只是用了很简单的一点点,需要的自己查。

用到一个”split“的方法,这里放一个教学链接 http://www.runoob.com/java/java-string-split.html

关闭文件

                input.close();

全部代码完整展示

import java.io.FileNotFoundException;
import java.util.*;

class NewBankAccount {
	int id;
	
	String name = new String();
	
	int balance;
	
	NewBankAccount(int id, String name){
		this.id = id;
		this.name = name;
		balance = 0;
	}
	
	NewBankAccount(int id, String name, int balance){
		this.id = id;
		this.name = name;
		this.balance = balance;
	}
	
	int getId() {
		return id;
	}
	
	String getName() {
		return name;
	}
	
	int getBalance() {
		return balance;
	}
	
	boolean deposit(int amount) {
		if (amount > 0) {
			balance = balance + amount;
			return true;
		} else {
			return false;
		}
	}
	
	boolean withdraw(int amount) {
		if ((amount > 0) && (amount <= balance)) {
			balance = balance - amount;
			return true;
		} else {
			return false;
		}
	}
}


public class Ex9 {

	public static void main(String[] args) throws FileNotFoundException {
		
		NewBankAccount[] list = new NewBankAccount[100];
				
		/*java.io.File file = new java.io.File("BankAccount.txt");
		 *Scanner input = new Scanner(file);
		 *这一段代码理论上的作用与下一行相同,但在实际运行中会从文档的第二行开始读取,暂时不知道错误在哪里。
		 */
		Scanner input = new Scanner(new java.io.File("BankAccount.txt"));
		
		while (input.hasNext()) {
			
			String line = input.nextLine();
			
			int i = 0;
			int id = 0;
			String name = null;
			int balance = 0;
			
			for (String retval: line.split(",")){
				
	            if (i == 0) {
	            	id = Integer.valueOf(retval);
	            }else if(i == 1) {
	            	name = retval;
	            }else if(i == 2) {
	            	balance = Integer.valueOf(retval);
	            }
	            
	            i = i + 1;
	        }
					
			list[id] = new NewBankAccount(id, name, balance);
			
			System.out.println("The current balance of "+list[id].getName()+" is "+list[id].getBalance());
		}
		
		input.close();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值