面向对象程序设计JAVA学习记录(4)

1.Conditionalize the withdraw Method

Objective

In this exercise you will modify the withdraw method to return a boolean value to specify if the transaction was successful.

Directions

Start by changing your working directory to previous on your computer.

  1. Create the banking directory. Copy the previous Banking project files in this package directory.

  2. Modify the Account class to conditionalize the withdraw and deposit methods.

    1. Modify the deposit method to return true. (meaning all deposits are successful)
    2. Modify the withdraw method to check that the amount being withdrawn is not greater than the current balance. If amt is less than balance, then subtract the amount from the balance and return true; else, leave the balance alone and return false.

  3. Put the preset code in the parent directory of banking directory, make necessary modifications, then compile and run the Main program. You shoud see the following output:
    Creating the customer Jane Smith. Creating her account with a 500.00 balance. Withdraw 150.00: true Deposit 22.50: true Withdraw 47.62: true Withdraw 400.00: false Customer [Smith, Jane] has a balance of 324.88 

    前置代码

    /* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
    /*
     * This class creates the program to test the banking classes.
     * It creates a new Bank, sets the Customer (with an initial balance),
     * and performs a series of transactions with the Account object.
     */
    //import banking.*;
    public class Main{
      public static void main(String[] args) {
        Customer customer;
        Account  account;
        // Create an account that can has a 500.00 balance.
        System.out.println("Creating the customer Jane Smith.");
        customer = new Customer("Jane", "Smith");
        System.out.println("Creating her account with a 500.00 balance.");
        customer.setAccount(new Account(500.00));
        account = customer.getAccount();
        // Perform some account transactions
        System.out.println("Withdraw 150.00: " + account.withdraw(150.00));
        System.out.println("Deposit 22.50: " + account.deposit(22.50));
        System.out.println("Withdraw 47.62: " + account.withdraw(47.62));
        System.out.println("Withdraw 400.00: " + account.withdraw(400.00));
        // Print out the final account balance
        System.out.println("Customer [" + customer.getLastName()
    		       + ", " + customer.getFirstName()
    		       + "] has a balance of " + account.getBalance());
      }
    }
    /* PRESET CODE END - NEVER TOUCH CODE ABOVE */

    这个题主要是读题,可知Account要传进Customer

    class Account{
      private double balance;
      public Account(double init_balance){
        balance=init_balance;
      }
      public double getBalance(){
        return balance;
      }
      public boolean deposit(double amt){
        balance+=amt;
        return true;
      }
      public boolean withdraw(double amt){
        if(balance >= amt){
          balance -= amt;
          return true;
        }
        else return false;
      }
    }
    class Customer{
      private String firstName;
      private String lastName;
      private Account account;
      public Customer (String f,String l){
        firstName = f;lastName = l;
      }
      public String getFirstName(){
        return firstName;
      }
      public String getLastName(){
        return lastName;
      }
      public Account getAccount(){
        return account;
      }
      public void setAccount(Account acct) {
        account = acct;
      }
    }

Use Arrays to Represent Associations

 

Objective

In this exercise you will use arrays to implement the multiplicity on the association between a bank and its customers.

扫描二维码关注公众号,回复: 14600043 查看本文章

Directions

Note: you must have completed the previous exercises of the banking project before this one.

To the banking package, you will add the Bank class as modeled by the UML diagram above. A bank object simply keeps track of an association between itself and its customers. We will implement this aggregate association with an array of Customer objects. We will also need to keep a integer attribute that keeps track of how many customers currently exist in the bank.

  1. Create the banking directory. Copy the previous Banking project files in this package directory.

  2. Add two attributes to the Bank class: customers (an array of Customer objects) and numberOfCustomers (an integer that keeps track of the next customers array index).

  3. Add a public constructor that initializes the customers array with some appropriate maximum size (at least bigger than 15).

  4. Add the addCustomer method. This method must construct a new Customer object from the parameters (first name, last name) and place it on the customers array. It must also increment the numberOfCustomers attribute.

  5. Add the getNumOfCustomers accessor method, which returns the numberOfCustomers attribute.

  6. Add the getCustomer method. This method returns the customer associated with the given index parameter.

  7. Compile and run the Main program. You shoud see the following output:
    Customer [1] is Simms, Jane Customer [2] is Bryant, Owen Customer [3] is Soley, Tim Customer [4] is Soley, Maria 

    上面那题的完善,读图即可完成 

前置代码

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.util.Scanner;
class Main {
	public static void main(String[] args) {
		Bank bank = new Bank();
		
		Scanner s = new Scanner(System.in);
		int t = s.nextInt();
		s.nextLine();
		while (t-- > 0){
			String f = s.next();
			String l = s.next();
			s.nextLine();
			bank.addCustomer(f, l);
		}
		for (int i = 0; i < bank.getNumOfCustomers(); i++) {
			Customer customer = bank.getCustomer(i);
			System.out.println("Customer [" + (i + 1) + "] is "
					+ customer.getLastName() + ", " + customer.getFirstName());
		}
	}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */

class Account{
    private double balance;
    public Account(double init_balance){
      balance=init_balance;
    }
    public double getBalance(){
      return balance;
    }
    public boolean deposit(double amt){
      balance+=amt;
      return true;
    }
    public boolean withdraw(double amt){
      if(balance >= amt){
        balance -= amt;
        return true;
      }
      else return false;
    }
  }
class Customer{
    private String firstName;
    private String lastName;
    private Account account;
    public Customer (String f,String l){
      firstName = f;lastName = l;
    }
    public String getFirstName(){
      return firstName;
    }
    public String getLastName(){
      return lastName;
    }
    public Account getAccount(){
      return account;
    }
    public void setAccount(Account acct) {
      account = acct;
    }
  }
class Bank{
  private Customer[] customers = new Customer [15];
  private int numberOfCustomers;
  public void addCustomer(String f ,String l) {
    customers[numberOfCustomers]=new Customer(f,l);
    numberOfCustomers++;
  }
  public int getNumOfCustomers() {
    return numberOfCustomers;
  }
  public Customer getCustomer(int index){
    return customers[index];
  }
}

 2.Manipulate Arrays

Objective

In this exercise you will have hands-on experience in declaring, creating, and manipulating one- and two-dimensional arrays of primitive types.

Directions

Using Simple Arrays

  1. Create an application class called Main. In the main() method, declare two variables called array1 and array2. They should be of type int[] (array of int).

  2. Using the curly-brace notation {}, initialize array1 to the first eight prime numbers: 2, 3, 5, 7, 11, 13, 17, and 19.

  3. Display the contents of array1. You may want to use the printArray method at the bottom of this page to display these integer arrays in a nice fashion. Compile Main and run it.

  4. Assign the array2 variable equal to the array1. Modify the even indexed element in array2 to be equal to the index value (for example, array2[0] = 0; and array2[2] = 2; etc). Print out array1. Compile Main and run it. What has happened to array1?

    Using Multi-Dimensional Arrays

  5. Declare a variable called matrix with the type of int[][] (an array of arrays of int).
    Intiailize the matrix to an array of five arrays.

  6. Populate each of the inner arrays in the following manner: Loop through the matrix from zero to its length; let's say that this index is i. On each iteration assign matrix[i] to a new array of integers the size of which is i.
    Then loop over each element in that array (of ints), with the index variable j. On each inner iteration assign matrix[i][j] to the value of i * j.

  7. Print the matrix by iterating over the outer array and printing each inner array on a separate line. Compile the Main class and run it. You should see an output similar to this:
    matrix[0] is <> 
    matrix[1] is <0> 
    matrix[2] is <0, 2> 
    matrix[3] is <0, 3, 6> 
    matrix[4] is <0, 4, 8, 12> 

Submit your final code only!

The printArray Support Method

 public static void printArray(int[] array) {
 System.out.print('<');
 for ( int i = 0; i < array.length; i++ ) { 
 // print an element
 System.out.print(array[i]); 
 // print a comma delimiter if not the last element 
 if ( (i + 1) < array.length ) { 
 System.out.print(", "); 
 }
 }
 System.out.print('>');
} 

 读题找到规律写出相应功能的代码

import java.util.*;
public class Main{
  public static void main(String[] args) {
    int[] array1 = {2,3,5,7,11,13,17,19};
    int[] array2 = array1;
    printArray(array1);
    for(int i = 0; i <= 7; i++){
      if(i%2 == 0){
        array2[i] = i;
      }
    }
    printArray(array2);
    int [][] matrix = new int[5][];
    for(int i = 0; i < 5; i++){
      matrix[i] = new int[i];
      for(int j = 0; j < i ; j++){
        matrix[i][j] = i*j;
      }
    }
    for(int i =0; i < 5; i++){
      System.out.printf("matrix[%d] is ", i);
      printArray(matrix[i]);
    }
  } 
  public static void printArray(int[] array) {
    System.out.print('<');
    for ( int i = 0; i < array.length; i++ ) { 
    System.out.print(array[i]); 
    if ((i + 1) < array.length) { 
    System.out.print(", "); 
    }
    }
    System.out.println('>');
  } 
}

3.Gift Givers

A group of NP (2 ≤ NP ≤ 10) uniquely named friends has decided to exchange gifts of money. Each of these friends might or might not give some money to any or all of the other friends. Likewise, each friend might or might not receive money from any or all of the other friends. Your goal in this problem is to deduce how much more money each person gives than they receive.

The rules for gift-giving are potentially different than you might expect. Each person sets aside a certain amount of money to give and divides this money evenly among all those to whom he or she is giving a gift. No fractional money is available, so dividing 3 among 2 friends would be 1 each for the friends with 1 left over -- that 1 left over stays in the giver's "account".

In any group of friends, some people are more giving than others (or at least may have more acquaintances) and some people have more money than others.

Given a group of friends, no one of whom has a name longer than 14 characters, the money each person in the group spends on gifts, and a (sub)list of friends to whom each person gives gifts, determine how much more (or less) each person in the group gives than they receive.

NOTE

The grader machine is a Linux machine that uses standard Unix conventions: end of line is a single character often known as '\n'. This differs from Windows, which ends lines with two charcters, '\n' and '\r'. Do not let your program get trapped by this!

INPUT

Line 1: The single integer, NP
Lines 2..NP+1: Each line contains the name of a group member
Lines NP+2..end: NP groups of lines organized like this:
The first line in the group tells the person's name who will be giving gifts.
The second line in the group contains two numbers: The initial amount of money (in the range 0..2000) to be divided up into gifts by the giver and then the number of people to whom the giver will give gifts, NGi (0 ≤ NGi ≤ NP-1).
If NGi is nonzero, each of the next NGi lines lists the the name of a recipient of a gift.

OUTPUT

The output is NP lines, each with the name of a person followed by a single blank followed by the net gain or loss (final_money_value - initial_money_value) for that person. The names should be printed in the same order they appear on line 2 of the input.

All gifts are integers. Each person gives the same integer amount of money to each friend to whom any money is given, and gives as much as possible that meets this constraint. Any money not given is kept by the giver.

SAMPLE INPUT

5
dave
laura
owen
vick
amr
dave
200 3
laura
owen
vick
owen
500 1
dave
amr
150 2
vick
owen
laura
0 2
amr
vick
vick
0 0

SAMPLE OUTPUT

dave 302
laura 66
owen -359
vick 141
amr -150

可以用一个字符串数组,一个数组,分别记录名字和钱,注意没有小数,花不完的钱会退回,不分给人时可以算是跳过一次循环,避免报错

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        String[] arr1 = new String[n+1];
        int[] arr2 = new int[n+1];
        for(int i = 0; i < n; i++){
            arr1[i] = s.next();
            arr2[i] = 0;
        }
        for(int m=0; m < n; m++){
            String give = s.next();
            int a = s.nextInt();
            int b = s.nextInt();
            if(b == 0) continue;
            int ave = a/b;
            for(int i = 0; i < n; i++){
                if(arr1[i].equals(give)){
                    arr2[i] -= ave*b;
                    break;
                }
            }
            for(int i = 0; i < b; i++){
                String get = s.next();
                for(int j = 0; j < n; j++){
                    if(arr1[j].equals(get)){
                        arr2[j] += ave;
                        break;
                    }
                }
            }
        } 
        for(int i = 0; i < n; i++){
            System.out.printf("%s %d\n",arr1[i],arr2[i]);
        }
        s.close();
    }
}

4.The N ordered crosses

The N ordered cross is defined as a graph produced by some special characters. An 1 ordered cross is shown like this:
 *
***
 *
Your problem is to generate the graph given the order N.

INPUT

An integer indicating the order of the cross.

OUTPUT

For the given order N, print the cross.

SAMPLE INPUT

2

SAMPLE OUTPUT

  *
  *
*****
  *
  *

找规律,用循环实现该功能

import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner s =new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++) System.out.printf(" ");
            System.out.println("*");
        }
        for(int i = 0; i < n*2; i++) System.out.printf("*");
        System.out.println("*");
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++) System.out.printf(" ");
            System.out.println("*");
        }
        s.close();
    }
}

猜你喜欢

转载自blog.csdn.net/lijj0304/article/details/127161306