본문 바로가기
솔루션모음/파워자바 프로그래밍

[파워자바] 21장 프로그래밍 솔루션 답지

by 이얏호이야호 2023. 2. 16.

 

1.

(1) java.lang.ArrayIndexOutOfBoundsException

(2)

try {
	int i = array[10];
} catch (ArrayIndexOutOfBoundsException e) {
	e.printStackTrace();
}
 

(3)

public static void sub() throws ArrayIndexOutOfBoundsException {
	int[] array = new int[10];
	int i = array[10];
}

 

2.

class MyException extends Exception  {
	public MyException(String message) { super(message);	}
}
public class MyExceptionTest {
	public static void checkNegative(int number) throws MyException {
		if (number < 0) {
			throw (new MyException("음수는 안됩니다."));
		}
		System.out.println("다행히 음수가 아니군요");
	}
	public static void main(String[] args) {
		try {
			checkNegative(1);
			checkNegative(-1);
		} catch (MyException ex) {	ex.printStackTrace();	}
	}
}

 

 

3.

import java.util.Scanner;
class NotFoundExecption extends Exception{
	public NotFoundExecption()
	{
		super("배열에서 찾을 수 없습니다.");
	}
}
public class Lab2 {
	public static int searchArray(int array[], int data) throws NotFoundExecption
	{
		for(int i=0;i<array.length;i++){
			if( array[i] == data )
				return i;
		}
		throw new NotFoundExecption();
	}
	public static void main(String[] arge)
	{
		Scanner sc=new Scanner(System.in);
		int[] a={0,1,2,3,4,5,6,7,8,9};
		int data=sc.nextInt();
		try {
			searchArray(a, data);
		} catch (NotFoundExecption e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

 

 

4.

import java.util.Scanner;
class NegativeBalanceException extends Exception
{
	public NegativeBalanceException(String message)
	{
		super(message);
	}
}
class BankAccount 
{
	private int balance=0;
	public int getBalance() {
		return balance;
	}
	public void setBalance(int balance) {
		this.balance = balance;
	}
	public void deposit(int amount)
	{
		balance += amount;
	}
	public void withdraw(int amount) throws NegativeBalanceException
	{
		if( balance < amount )
			throw new NegativeBalanceException("잔고가 음수입니다.");
		balance -= amount;
	}
}
public class BankAccountTest {
	public static void main(String[] arge)
	{
		BankAccount ba = new BankAccount();
		ba.deposit(100);
		try {
			ba.withdraw(200);
		} catch (NegativeBalanceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

 

댓글