# Notes

Make use of methods to implement arrays. Arrays can be passed into parameter list and can be returned in the method block.
利用方法实现数组。 数组可以传递到参数列表中,并可以在方法块中返回。
Ex.

  1. Create array 创建数组
  2. Print array 打印数组
  3. Sort array (swapping elements by position) 对数组排序(按位置交换元素)
  4. Search array 搜索数组
  5. Highest value in array 数组中的最大值
  6. Lowest value in array 数组中的最小值
  7. Remove item (s) from array 从数组中删除元素
  8. Update item (s) from array 从数组更新元素

# Arrays vs ArrayLists intro

A challenge – merge two arrays together!
Have method to take in two arrays and return the merged array in sorted order.
将两个数组合并在一起!
想办法接受两个数组,并按顺序合并数组。

# Method 1

Check sizes of each array ( arrays X and Y )
Set size of new array to be merged ( array M )
Loop thru each array based on length of each array
Track current position of merged array M
Store each array value into new array M 
Return array M
public static int[] mergeArray(int[]arrayX, int[]arrayY) {
        //  The size of the new array will be the sum of arrayX and arrayY sizes
        int[] arrayM = new int[arrayX.length + arrayY.length];
        int i = 0, j = 0, currentPos = 0;
        //  Loop 1
        while (i < arrayX.length)  
           arrayM[currentPos++] = arrayX[i++];
        
        //  loop 2 
         while (j < arrayY.length)   
            arrayM[currentPos++] = arrayY[j++];
            
        return arrayM;
}

# Method 2

ArrayList use case for merging 2 arrays

import java.util.ArrayList;
import java.util.Arrays;
//merge two arrays into an ArrayList
class MyMerge {
    public static void main(String args[]) {
        int[] a = { 1, 2, 3, 4 }; // Simple Array of integers 1 thru 4
        int[] b = { 5, 6, 7, 8, 9, 10 }; // Simple Array of integers 5 thru 10
        // Use dynamic Array list to hold merge of a and b 1 thru 10
        ArrayList<Integer> arrMerge = new ArrayList<Integer>();
        for (int i = 0; i < a.length; i++) // Loop thru array a and merge all items in a
        {
            arrMerge.add(a[i]);
        }
        for (int i = 0; i < b.length; i++) // Loop thru array b and merge all items from b
        {
            arrMerge.add(b[i]);
        }
        System.out.println(arrMerge); // Print Contents of final merged array
    }
}

Result:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Java built in methods can do the trick!

import java.util.*;
public class bSearch2 {
    
    public static void main(String [] args)
    {
        int[] myArray={5,4,3,2,1};
        
        Arrays.sort(myArray);
        
        int result = Arrays.binarySearch(myArray, 3);
        
        System.out.println((result >= 0 ? "Is found " : "Is not found ") +
                         " \nfound at position " + result);
    }
}

Bsearch trace revisited follows…

# Optimizing code

Finding the next best value in array if present!

import java.util.Arrays;
// classic case – BUT include next best value if Key is not present or found.
public class BSearch {
    
    public static int bs(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        int mid=0;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            mid = (int) (hi + lo) / 2;
            if (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return lo==hi ? mid : hi + 1;
    }
public static void main(String[] args) {
         
    int arr [] = new int[] {1,2,3,4,12,16};
    //sort the array
    Arrays.sort(arr);
    int i= bs(arr,2); //search for key item 2 from list 
    System.out.println(Math.abs(arr[i]));
    }
}

# Split function working in conjunction with an array

拆分函数与数组结合使用

The string split() method breaks a given string ("tokenizes") around matches of the given regular expression.

String line = "a,b,c";
String splitter[] = line.split(",");
splitter[0] = "a";
splitter[1] = "b";
splitter[2] = "c";
// traverse data
// traditional loop
for (int i = 0; i < splitter.length; ++i)
    System.out.println(splitter[i]);
    System.out.println();
// or use for enhanced or "for each" loop
for (String sObj : splitter)
    System.out.println(sObj);

Result:
结果均为

a
b
c

# Lab

  • PROJECT
    Bank record generations

  • Objective
    To write a program that parses and processes bank data from a file.

# PROJECT DESCRIPTION

Bank of IIT has gotten their hands on some interesting data which will allow for possible loans to various clients from various regions.

Accompanying the labs specs is a csv (comma separated value) file named
bank-Detail.csv which contains valuable raw data to allow the bank to process loans based on client details from the file.

You need to parse the data and print record data for future loan considerations.

# Project Details

  1. Create an abstract class called Client.java to allow for three abstract methods the bank needs to process. Name your methods readData() , processData() and printData() . No arguments are needed for your methods.

  2. Create a BankRecords.java file which will utilize the Client asbtract methods and generate ultimately the client records from the csv file.

    The client file has the following header information

    id {string} 
    age {numeric}
    sex {FEMALE,MALE}
    region {INNER_CITY,TOWN,RURAL,SUBURBAN}
    income {numeric}
    married {NO,YES}
    children {0,1,2,3}
    car {NO,YES}
    save_act {NO,YES}
    current_act {NO,YES}
    mortgage {NO,YES}
    pep {YES,NO}

    Create instance fields with appropriate data types for each header item above in your class. Include getter and setters for each instance field.

  3. Include code definitions for each method declared in your Client class as follows

    • Your readData() method should read in all the record data from the csv file in your path into an ArrayList.
    • Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters. Use an array of objects to store record data for each instance field.
    • Your printData() method should print the first 25 records for various fields to the console via your getters. Print records for the following fields: ID , AGE , SEX , REGION , INCOME , and MORTGAGE .
  4. Include headings in your print detail.Printing record detail should be in a neat columnar style format.

Make sure to include a try catch block when reading any file!
Include also proper exception handling.
Include your project’s entire source code/csv file into a zip file, and in a separate Word file, your output snapshot/program description/source code as well.

# Objectives

# UML Design of classes

classDiagram
    BankRecords --> Client
    BankRecords -- BankRecordsTest
    class BankRecords{
        robjs[] : new BankRecords[600]
		array: ArrayList&lt;List&lt;String&gt;&gt;
        -id:string
        -age:int
        -sex:String
        -region:String
        -income:double
        -married:String
        -children:int
        -car:String
        -save_act:String
        -current_act:String
        -mortgage:String
        -pep:String
        +getId():String
        +getAge():Int
        +setId(id:String)
        +setAge(age:int)
        +readData()*
        +processData()*
        +printData()*
    }
    class Client{
        +readData()*
        +processData()*
        +printData()*
    }
    class BankRecordsTest{
        +main()
    }
  1. Client.java source setup

    Create class file as abstract

    Include 3 abstract methods inheritable for your BankRecords class.

    Ex. of abstract method.

    public abstract class Client {
        public abstract void readData();  //read file detail
           
        //finish remaining methods
    }
  2. BankRecords.java source setup

    • Add .csv source file to your project folder
      Take your .csv file and add it to the root of your project folder.

    • Create necessary class variables

    //setup static objects for IO processing
    //array of BankRecords objects
    static BankRecords robjs[] = new BankRecords[600]; 
    //arraylist to hold spreadsheet rows & columns
    static ArrayList<List<String>> array = new ArrayList<>();  
    //instance fields
    private String id;
    private int age;
    /*create remaining instance fields with appropriate data types*/
    • Generate getters & setters for ALL your instance fields
      From your menu go to Source > Generate Getters and Setters…

    even though we don’t need all getters and setters for this lab, we may need them in subsequent labs!

    • Setup class functions to perform the following tasks

      Read data from spreadsheet
      public void readData() {
              
          BufferedReader br;
          //initialize reader object and set file path to root of project
          br = new BufferedReader(new FileReader (new File("bank-Detail.csv")));
          String line;
          //read each record in csv file
          while ((line = br.readLine()) != null) {
              //parse each record in csv file by a comma ( , )
              //into a list stored in the arraylist-> Arrays
              array.add(Arrays.asList(line.split(",")));
          }
              
          processData();  //call function for processing record data
      }
      Process data from arraylist
      public void processData() {
          //create index for array while iterating thru arraylist
          int idx=0;
          //create for each loop to cycle thru arraylist of values 
          //and PASS that data into your record objects' setters 
          for (List<String> rowData: array) {
              //initialize array of objects
              robjs[idx] = new BankRecords();
              //call setters below and populate them, item by item
              robjs[idx].setId(rowData.get(0)); //get 1st column
              robjs[idx].setAge(Integer.parseInt(rowData.get(1))); //get 2nd column
              /*continue processing arraylist item values into each array object -> robjs[] by index*/
              idx++;
          }
          printData();  //call function to print objects held in memory
      }
      Print data from array
      public void printData() {                    
              //1. Set appropriate headings for displaying first 25 records
              //2. Create for loop and print each record objects instance data 
              //3. Within for loop use appropriate formatting techniques to print out record detail  
          }

# Error trappings!

Make sure to include appropriate exception handling with try catch blocks for any file being processed.

*Make use of such runtime exceptions such as FileNotFoundException or other possible exceptions that may occur during the processing of any file(s).

Use various print formatting for printing detailed record information especially to make output look professional and columnar like with the format specifier % symbol followed by a converter.

Popular converters to use include:

%ffloat
%dint
%sstring
%nnewline

Ex. of an appropriate heading that can be printed may be as follows:

System.out.println("ID\t\tAGE\t\tSEX\t\tREGION\t\tINCOME\t\tMORTGAGE");

# code

BankRecords.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BankRecords extends Client {
    //setup static objects for IO processing
    //array of BankRecords objects
    static BankRecords robjs[] = new BankRecords[600]; 
    //arraylist to hold spreadsheet rows & columns
    static ArrayList<List<String>> array = new ArrayList<>();  
    //instance fields
    private String id;
    private int age;
    private String sex;
    private String region;
    private double income;
    private String married;
    private int children;
    private String car;
    private String save_act;
    private String current_act;
    private String mortgage;
    private String pep; 
    
    @Override
    public void readData() {
        BufferedReader br = null;
        //initialize reader object and set file path to root of project
        try {
            br = new BufferedReader(new FileReader (new File("bank-Detail.csv")));
            String line;
            //read each record in csv file
            while ((line = br.readLine()) != null) {
                //parse each record in csv file by a comma ( , )
                //into a list stored in the arraylist-> Arrays
                array.add(Arrays.asList(line.split(",")));
            }
        } catch (Exception e) {
            System.err.println("There was a problem loading the file");
        }
        
        processData();  //call function for processing record data
    }
    
    @Override
    public void processData() {
        //create index for array while iterating thru arraylist
        int idx=0;
        
        //create for each loop to cycle thru arraylist of values 
        //and PASS that data into your record objects' setters 
        for (List<String> rowData: array) {
            //initialize array of objects
            robjs[idx] = new BankRecords();
            //call setters below and populate them, item by item
            robjs[idx].setId(rowData.get(0)); //get 1st column
            robjs[idx].setAge(Integer.parseInt(rowData.get(1))); //get 2nd column
            robjs[idx].setSex(rowData.get(2));
            robjs[idx].setRegion(rowData.get(3));
            robjs[idx].setIncome(Double.parseDouble(rowData.get(4)));
            robjs[idx].setMarried(rowData.get(5));
            robjs[idx].setChildren(Integer.parseInt(rowData.get(6)));
            robjs[idx].setCar(rowData.get(7));
            robjs[idx].setSave_act(rowData.get(8));
            robjs[idx].setCurrent_act(rowData.get(9));
            robjs[idx].setMortgage(rowData.get(10));
            robjs[idx].setPep(rowData.get(11));
            /*continue processing arraylist item values into each array object -> robjs[] by index*/
            idx++;
        }
        
        printData();  //call function to print objects held in memory       
    }
    
    @Override
    public void printData() {
        //1. Set appropriate headings for displaying first 25 records
        //2. Create for loop and print each record objects instance data 
        //3. Within for loop use appropriate formatting techniques to print out record detail  
        
        //Set heading
        System.out.printf("First 25 Client details:\n\n%-10s\t%-10s\t%-10s\t%-10s\t%-10s\t%-10s\n", "ID","Age","Sex","Region","Income","Mortgage");
        
        for (int i=0;i<25;i++){
            
            String s=String.format("%-10s\t%-10d\t%-10s\t%-10s\t%-10.2f\t%-10s", 
                    robjs[i].getId(),robjs[i].getAge(),robjs[i].getSex(),robjs[i].getRegion(),robjs[i].getIncome(),robjs[i].getMortgage());
            System.out.println(s);
            
        }
    }   
    
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }
    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }
    /**
     * @return the sex
     */
    public String getSex() {
        return sex;
    }
    /**
     * @param sex the sex to set
     */
    public void setSex(String sex) {
        this.sex = sex;
    }
    /**
     * @return the region
     */
    public String getRegion() {
        return region;
    }
    /**
     * @param region the region to set
     */
    public void setRegion(String region) {
        this.region = region;
    }
    /**
     * @return the income
     */
    public double getIncome() {
        return income;
    }
    /**
     * @param income the income to set
     */
    public void setIncome(double income) {
        this.income = income;
    }
    /**
     * @return the married
     */
    public String getMarried() {
        return married;
    }
    /**
     * @param married the married to set
     */
    public void setMarried(String married) {
        this.married = married;
    }
    /**
     * @return the children
     */
    public int getChildren() {
        return children;
    }
    /**
     * @param children the children to set
     */
    public void setChildren(int children) {
        this.children = children;
    }
    /**
     * @return the car
     */
    public String getCar() {
        return car;
    }
    /**
     * @param car the car to set
     */
    public void setCar(String car) {
        this.car = car;
    }
    /**
     * @return the save_act
     */
    public String getSave_act() {
        return save_act;
    }
    /**
     * @param save_act the save_act to set
     */
    public void setSave_act(String save_act) {
        this.save_act = save_act;
    }
    /**
     * @return the current_act
     */
    public String getCurrent_act() {
        return current_act;
    }
    /**
     * @param current_act the current_act to set
     */
    public void setCurrent_act(String current_act) {
        this.current_act = current_act;
    }
    /**
     * @return the mortgage
     */
    public String getMortgage() {
        return mortgage;
    }
    /**
     * @param mortgage the mortgage to set
     */
    public void setMortgage(String mortgage) {
        this.mortgage = mortgage;
    }
    /**
     * @return the pep
     */
    public String getPep() {
        return pep;
    }
    /**
     * @param pep the pep to set
     */
    public void setPep(String pep) {
        this.pep = pep;
    }   
}
BankRecordsTest.java
public class BankRecordsTest {
    public static void main(String[] args) {
        BankRecords br = new BankRecords();
        br.readData();
    }
}
Client.java
public abstract class Client {
    public abstract void readData();  //read file detail
    public abstract void processData(); //process file detail
    public abstract void printData(); //print file detail
     
}
阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Ruri Shimotsuki 微信支付

微信支付

Ruri Shimotsuki 支付宝

支付宝

Ruri Shimotsuki 贝宝

贝宝