Application Software

mobile-apps-pile-ss-1920.jpg
Various application softwares, Retrieved from MediaIndia

Introduction:

Applications softwares are programs that are used to perform certain task for users. In the hierarchy of software, it is parallel with system softwares (The OS we talked about earlier). I will introduce three types of application softwares, the release and update strategies of application softwares, and GUI vs. GLI.

General-purpose software

This kind of softwares can perform a variety of tasks, and they are not constrained to a particular function. Here are a few common general purpose softwares:

Word processor

unnamed.png
An Example: Microsoft Word. Picture: GooglePlay

 

Word processor are used to manipulate user input text, format it, and output a printout. It can be used to achieve multiple purposes,

like making poster, taking notes, printing out documents, etc.

Spreadsheet

It’s a software that manipulate data in columns and rows. It can also be used to analyze data and draw graphs. It’s usually used by a single user.

Database Management Systems

DBMS-database-management-system.png
Source: TechTarget

It manages database and can be used by multiple users. Unlike spreadsheet, it accepts more different data associations.

Specific software

In contrast, specific softwares are designed to perform one particular function.

Email Clients: Used to access, manage, send emails.

Web Browsers: Used to access, present, and find information on the World Wide Web.

6-browser-icons2
Jonathan Hodgson

Computer Aided Design (CAD): Programs that help users create, modify, analyze, or optimize their design.

Graphic Processing Software: Programs that help users create, present, edit, and analyze visual images.

Bespoke software

Bespoke softwares are tailor made for one particular user and purpose. Here are some examples:

For military: Bespoke software may include programs that control missiles, drones, or other military device.

For medical organization: Programs for medical equipment, or management of data inside the organization.

For financial institutions: Programs that analyze data in these institutions, control bank accounts, etc.

Management of Updates

It’s crucial for application software developers to further improve their products. There are several types of updates:

Patches – usually fix bugs of an existing software

Upgrades – include novel function and fix bug, usually paid

Updates – minor bug fix, usually free

Releases – final and working version, new (after α&β testing) or updated software

Automatic vs. Manual Update

prosconsautomanual.png

 

Graphical User Interface (GUI)

As a link between the hardware, system software, and application softwares, a Graphic User Interface provide ways of user interaction with the softwares. Common GUI features are provided in libraries as well as what happens when the window is moved or minimized. However, certain parts of interface vary according to the app.  It greatly improves usability.

Common Features of Apps (GUI elements)

Toolbars: An area include buttons, menus, and other input/output elements.

Menus: Display a list of command

Dialogue boxes: Used to communicate with user can let user choose from provided options.

GUI components (WIMP): windows, icons, menus, and pointers.

CLI vs. GUI

GUICLI.png

 

Operating System

maxresdefault.jpg
By OpenCanvas

Operating system is made up of a set of softwares which controls the resources of hardware and also provide services for applications. It is like the bridge between hardware and application softwares.

Major OS are MacOS, Windows, Linux, etc.

There are four main managers: memory manager, process manager, device manager, and file manager. In the following blog post I will explain each of them in detail.

Memory Manager

WX20171205-160952@2x.png
Dynamic partitions by OpenCanvas

It’s responsible for allocating and deallocating resources. There are three ways of managing memory.

Single user contiguous

The memory takes in one job, then process and clear, and then process the next job.

If the job’s size is larger than memory avaible, it will not be executed.

Disadvantage: impractical for complex system

Contiguous Partitions

Fixed partitions

More than a single job are stored in partition memory table to keep track of their usage. The partition is static unless re-boot.

dynamic partitions

Give memory requested, so memory is not wasted.

When memory is deallocated (cleared to make free), adjacent blocks are joined.

Allocation methods for contiguous partitions

– first fit allocation: use first eligible partition
– best fit allocation: look for the smallest: slower but more efficient.

Non-Contiguous Partitions

Instead of storing the whole program, we can split the job. In this case we use virtual memory.

There are 4 schemes:

Paged map allocation

Divide jobs to equal sized parts.

The sections of disk are called sectors/blocks; section of the main memory is call page frames.

preparation steps: 1. determine No. of pages in the program, 2. locate empty page frames.

Disadvantage: Since there is need to track the jobs, complexity is increased.

There are three tables:
1. Job table, which includes Job’s size & PMT
2. Page map table (PMT), includes page No. & page frame No.
3. Memory map table includes page frame&state.

Demand paging

Pages are loaded on demand; Page map table adds three columns: “status, modified, referenced.”

Page replacement policy determines how to replace page:
1. first in first out
2. least recently used
3. least frequently used
4. most recently used

Segmented memory allocation

Split to segments that reflect the nature and structure of the code.

Segment map table: segment No. & page pointer

Mixture of segmented memory allocation & demand paging memory allocation

It combines the logic of segmented memory allocation and the physical benefit of paging; It uses both segment map table and page map table plus the information of read, write, and execute. Disadvantage: Too complex for keeping track of all the information.

Why virtual memory good?

It uses back up memory, hard drive, to extend memory capacity.

Process Manager

Three factors that affect the processing: performance, speed, bandwidth.

CPU has its clock speed, and its bandwidth determines how much info can be processed in one instruction.

The processor’s memory is cache, which is 5/10 faster than RAM.

process scheduler

It includes job scheduler and process scheduler.

For each job, there may be multiple processes.

5 states of processing:
hold: job schedule hold the process,
ready: and the process is into a ready state
run: the the job is processed. Concern the performance, it might go back to ready state. If there’s a process failure (it shows IO request page fault),
wait: then it will wait until it finds correct resource.
finish

Process control block: contain information about jobs, which are placed in queue.

Three limitations scheduling policy

  1. Finite number of resource
  2. Locked resources, meaning that they are not shared.
  3. Need the user to reassign jobs.

We don’t want resource hogging: a job make use of all resources, need to intervene.

Pre-emptive

The system is able to intervene the process, examples:

  1. Pre-emptive version of SJN: shortest remaining time(SJN);
  2. Round robin, there is predetermine time slice given to each job, called a time quantum. When the time expired, the job changes and waits in queue;
WX20171205-161143@2x.png
Round Robin, by OpenCanvas

Non pre-emptive

System need to wait for the each process to complete, examples:

  1. First come first serve (FCFS), response time is not efficient; unpredictable;
  2. SJN: short job next. It needs accurate run-time estimate;
  3. Priority scheduling: administrator first, user’s basic process later.

Multiple level queue: multi priority, variable time quantums, aging queue.

Three problems of scheduling:

Deadlock: all resources are locked.
Livelock: some resources are released but put back to locked state.
Starvation: one process always gets resource, others always wait.

Device Manager

It controls the external devices in coordination with the internal system.

4 responsibilities

1. status of each device
2. enforce policies
3. allocation
4. diallocation

3 types of devices

  1. dedicated device: one at a time, like printers
  2. shared device: assigned to multiple processes,
  3. virtual devices: spooler, which controlled by program. Put job in queue and take them one at a time. Good spooler can cancel or reorder the jobs.

Direct access storage

  1. Fix head magnetic disk storage: The circles on the disk are called tracks. It has fixed r/w heads.
  2. Movable head magnetic disk (hard disk): It has 1 read-write head. Adv: more space for data, reduced cost; Dis: constrained by the speed of the moving head.
  3. Optical disk storage: It moves at constant angular velocity. It uses laser to access the data. Blue ray disk can store data in thinner layers, thus increasing storage.
  4. Flash memory: It is electrical erasable programmable (EEP) read-only memory. It was used to boot-up (ROM), but now it is used in more scenarios like Solid State Drives.

File Manager

It is related to the managing of data, program, compiler, installed applications, and set permissions of access, etc.

It is in charge of physical component, information resources, and policies.

Its 4 tasks

  1. Keep track of where each file is store,
  2. Use a policy to determine how the file should be store,
  3. Allocate each file when the user has been cleared for access.
  4. Deallocate the file when it is returned to storage.

Network manager

It provides a way for users to share hardware and software resources while controlling users access.

GUI

OS has to provide a link between the user and the computer hardware, and GUI is the solution

Types of user interfaces

Linux_command-line._Bash._GNOME_Terminal._screenshot.png
CLI. From Wiki

Graphical User Interfaces (GUIs);
Command Line Interfaces (CLIs);
Natural Language Interface (NLIs);
Menu Based Interface (MBIs);

The MacOS and Windows are both GUIs. Linux might have CLIs when there is no GUI.

Conclusion:

Operating system is the foundation of all the application softwares. As the hierarchy of software shows, software includes system softwares and applications softwares. System softwares connect the hardware to provide crucial service to applications. Therefore, it’s important to know how the OS works in order to better understand computers.

 

 

One Dimensional Array

In this blog post I will share my answer to the programming activity in Chapter 8 of Java Illuminated Fourth Edition.

0

This is the class diagram of the program. The BarChart class mainly focus on the graphics and presentation of the array. The ArrayPractice1 class includes the exercises, and it also uses the BarChart object. Here are the exercises.

Exercise #1

Prints the array to the console with elements separated by a space. The instance variable arr is the integer array to be printed.

Answer:

public void printArray( )
{
    for ( int i = 0;i < arr.length; i++ )
    {
        System.out.print (arr[i] + ” “);
        animate( i );
    }
}

Explanation:

According to the question, I need to print every element in the array. The only way that we can go through the elements in the array is by using index. I used a for loop and use “i” as the index. I print out the element of index “i” and add a space after it. After that, i is incremented so that the next element will be printed.

Output:

Picture1

Exercise #2

Sets all the elements in the array to parameter value. The instance variable arr is the integer array to be processed.

Answer:

for ( int i = 0;i < arr.length; i++ )
{
    arr[i] = value;
    animate( i );
}

Explanation:

Using another for loop, I assign the integer “value” to every element in the array. If, in the future, we need to assign different value to the array, we can use the index “i” the differentiate the values.

Output:

2

Exercise #3

Counts number of elements equal to parameter value. The instance variable arr is the integer array to be processed.

Answer:

int fre = 0;
for (int i = 0; i< arr.length ; i++){
    if (arr[i] == value){
        fre ++;
    }
    animate( i , fre );
}
return fre;

Explanation:

To count the frequency, we need to declare an integer variable outside the for loop so that when the loop ends the value will not be deleted. Then, for each time the element equals the value, the frequency variable increments.

Output:

3

Exercise #4

Finds and returns the minimum value in arr. The instance variable arr is the integer array to be processed.

Answer:

int min = arr[0];
for (int i = 0; i < arr.length ; i++){
    if (arr[i] <= min){
        min = arr[i];
    }
animate( i, min );
}
return min;

Explanation:

To find the minimum value, we need to first declare a variable that holds the min value. Then, in the for loop, overtime we find a value smaller than the min value, we update the min variable by assigning the value of that element into it. The for loop will go through the array and compare every value with the current minimum one.

Output:

4

Conclusion: Real Life Implication

The array is very useful since we often need to analyse data and present data in a organised way. These exercises help me to familiarise myself with one dimensional array and the methods related to it. In real life, we can use one dimensional array in statistic, and use this program to present the statistic. Also, we can use array to search in a big bunch of data, and also to present a large amount of data efficiently. We can also incorporate array in GUI, which enables us to present the array visually.

 

Inheritance – Programming Activity

After we learned inheritance in class, we were assigned an programming activity which is in 10.4 of the textbook Java Illuminated Fourth Edition.

Generally, this programming activity is to use inheritance to create a subclass of the BankAccount class which we coded earlier. Also, we will create a client of the SavingAccount class which will show how it works.

Exercise

The textbook asks me to copy the source file, and add more to the class according to the instructions.

Exercise 1 & 2 – inheritance/instance variable

Question:

  • indicate that SavingAccount inherits from BankAccount
  • define the private interestRate instance variable (a double, annual rate)
public class SavingsAccount extends BankAccount
{
 public final double DEFAULT_RATE = .03;
 private double interestRate;
...

To inherit from a super class, I need to use the keyword “extends” plus superclass name.

Although now this class is a subclass of BankAccount class, we can add more instance variables, which is called specialisation. Therefore, I directly add a private double variable here. It is private so that its subclass will not be able to directly access it.

Exercise 3 -default constructor

  • write the default constructor (explicitly call the BankAccount Default constructor, set interestRate to default value DEFAULT_RATE, print a message indicating that the constructor is called.)
public SavingsAccount(){
  super();
  //This is explicit, 
  //while implicit means 
  //even if you do not call it, 
  //the default constructor 
  //will be called.
  interestRate = DEFAULT_RATE;
  System.out.println("Default Constructor is called.");
 }

To explicit call the constructor of the super class, BankAccount, I used “super()” which calls the constructor of super class that has not argument. To indicate the constructor is called, I let the system print out a message.

The output will be:

1

This will show up when I create a new object of the subclass using the explicit call of the super class’s default constructor.

Exercise 4 – overloaded constructor

public SavingsAccount(double startBalance, double startInterestRate){
    super(startBalance);
    setInterestRate(startInterestRate);
    System.out.println("Overloaded constructor is called.");
 }

This time I called the overloaded constructor of the super class. This constructor has arguments, so that when you call the super class’s overloaded constructor, you need to include the correct arguments.

2

The output will be like this:

3

The message helps me to make sure which constructor is called.

Exercise 5 – mutator method

This asks me to write a void-return-type method that can implement the interest rate.  It will call the deposit method and pass a month’s worth of interest.

public void applyInterest(){
     deposit(getBalance()*interestRate);
}

Since the interest rate is for a month, I used an accessor method to get the balance and multiplies the monthly interest rate. Then I called the deposit method, which is inherited from the super class.

Exercise 6 – toString method

  • This is returns formatted balance and interestRate.
  • invokes superclass toString to format balance
  • formats interestRate as percent using a NumberFormat object
  • also use the gerPercentInstance method in the NumberFormat class.
public String toString(){
    //return formatted balance and interestRate
    return (super.toString() +
    " Interest rate is " + 
    NumberFormat.getPercentInstance().format(interestRate));
}

In this method I used “super.” notation to call the toString method in the super class. Then I actually override the toString method by adding a formatted interest rate using number format.

The output will be:

4

Conclusion

In this program, I practiced writing a subclass using inheritance. I distinguished between overload and override. I may use what I learned in these exercise into my future programs. I also found out that inheritance is a very efficient way of writing codes because it save codes and make it easier to write similar classes and also to make classes to be specialised.

Reading Assignment

This assignment is to read through chapter 3.15, 12.7 and 12.9 of the book Java Illuminated (sixth edition). From these chapters, I learned about wrapper class, as well as radio button, checkboxes, and drop-down list (combo box). I will mainly talk about wrapper class and some examples of it.

Picture1
From Java Illuminated. These are corresponding wrapper class for the primitive data types.

The Integer, Double, and Other Wrapper Classes

The reason for the name Wrapper class is that this class “wrap” the primitive data type into objects. This class provides methods to convert between objects and primitive data types.

To convert a primitive data type variable into a object, we can instantiate a new object, passing the primitive variable as an argument:

int a = 1;
Integer integerObject = new Integer(a);

As we can see here, the name of the wrapper class is similar to the name of the primitive data type. Specifically, the names of the wrapper classes starts with capital letter, and they are complete words. (ie. char is Character)

If I write the previous code like this:

int a = 1;
Integer integerObject = a;

This is called autoboxing, because the class automatically does the conversion for us.

If we use Integer object in an arithmetic expression, like:

sum = a + integerObject;

The program will add the two int variables together. This is called unboxing. Here the class convert the object to primitive type automatically.

Parse Method

Inside the wrapper classes, there are static methods that can be used to convert String to different objects or primitive data type.

For example, if we have a String “12.0”, and we want to use it as a double, we can use dot notation to use the method in the Double wrapper class:

double doublePrimitiveType = Double.parseDouble("12.0");

Then the variable doublePrimitiveType will be assigned the double 12.0. Similarly, if we want to get the double object, we can write like this:

Double doubleObject = Double.valueOf("12.0");

Then the double object is assigned to the variable doubleObject.

As this is an example for Double class, we can just replace the part of word after “parse__” to convert other types of data and objects.

Conclusion

The wrapper class is necessary because there needs to be a way of converting between different primitive data types. Also, when the conversion is lossy, we need to consider what is omitted and what is left.

Structured Text File: 6 Exercises

After we learned the classes and methods related to the File I/O, we did 6 exercises to test our understanding. In this blog post, I will focus on these six exercises and my reflection about them.

Questions and Answers

Q1

Write a program that reads a file that contains only one line; output all the characters, one character per line.1

Here is the result of the program. I used the method from Scanner Class, useDelimiter(), to separate every character. Since the question asks me to print all the characters line by line, I used the delimiter “”.

Q2

Write a program that reads a file and counts how many lines it contains.

2

I think this problem is simpler than the previous one, since what I need to do is construct a while loop using “inputStream.hasNextLine()”, while using a integer variable to record the time of looping.

Q3

Write a program that reads a text file that contains a grade (for instance, 87) on each line. Calculate and print the average of the grades.

  1. 3

This problem requires a similar algorithm as the previous one, as we need to use

inputStream.hasNextLine()

Then, we put the each line in a variable, and add them together. However, there is a problem because the data type of the lines is String. Therefore, we can use wrapper class, Integer, to convert the String into integer data type. This is what I used:

item = Integer.parseInt(line);

Also, we need a try catch block to handle the error “InputMismatchException.”

Q4

Design a class that checks if the contents of two text files are identical and, if not, determines how many lines are different. //Lines are different if they differ in one or more characters.//Test your class with a client program, which contains main() method

4

To deal with this seeming difficult problem, I first create a Scanner for the two InputStreams, which are the two files. Then, I use the a while loop to count the same lines. I wrote three conditions: The first has next line; the second has next line; they are equal (represented by a boolean variable declared in advance). Here are the codes for this part:

int number = 0;
int a = 0;
int b = 0;
boolean equal = true;
while (input1.hasNextLine() && input2.hasNextLine() && equal){
    String garbage1 = input1.nextLine();
    String garbage2 = input2.nextLine();
    if(garbage1.equals(garbage2)){
        number ++;
    } else {
        a += 1;
        b += 1;
        equal = false;
    }
}

To read the text line by line, I used garbage variables to accept the data in each line while counting the number of lines. After finding the number of same lines, I used two while loops to count lines that are left out, which gives me the number of different lines.

Q5

In Internet programming, programmers receive parameters via a query string, which looks like a String with fields separated by the “&” character. Each field typically has a metadata part and a data part separated by the equal sign. An example of a query string is: “first=Mike&last=Jones&id=mike1&password=hello”

Using Scanner at least once, parse a query string and output each field on a different line after replacing the equal sign with a colon followed by a space. For example, for the preceding sample query string, the output should be: first: Mikelast: Jonesid: mike1password: hello

5

The aim is to re-format the line. So I must use delimiter to separate the line with “&” and then “=”. I chose to use ArrayList to gather all the lines, since it is easy for me to go through each item it the list. Firstly, I use the delimiter “&” and put each item in an ArrayList named “info.” Then, here is what I got for the second delimiter:

int i = 0;
for (String item: info){
    Scanner parse2 = new Scanner(item);
    parse2.useDelimiter("=");
    info.set(i,"" + parse2.next() + ": " + parse2.next());
    i++;
}

I initialise an integer i control the number of the loop. Also, it provides me index so that I can use the method “.set(index,argument)” this for each loop. In the argument, I formatted the line in my own way.

Q6

Design a class that attempts to determine the relative frequency of each letter by reading a file and keeping track of the number of times each of the 26 English alphabet characters appears.Also provide methods, such as highestFrequencyCharacter and lowestFrequencyCharacter.Test your class with a client program.

6

This program is a little tricky. Firstly, to separate all the characters, I used delimiter “” again. I create a method which takes the file name and a character as arguments. Inside the method, I use while loop and an integer variable to record the number of times that the character appears. When I get the character, I use charAt(0) for each line I separated using delimiter.

 

Real Life Implication

There are many real life implications of these exercises. The first program can be improved to be able to count characters. The second one is useful because it can count line in a file. The third can be used by teachers to calculate the average grade out of a file that records all the grades. The fifth one can be used when we need to unpack some messages that have particular pattern. It’s very useful for changing the format of some documents. The six one can be used in cryptography, since determining the frequency of characters can help us discover the plain code of a cypher.

Conclusion

By doing these exercises, we solidified our knowledge about File I/O. Also, I am inspired by these programs so that I can create some similar programs to solve my daily-life problems. It’s so much fun to create programs that do complicated jobs!

File I/O

Last week, we began to learn about the input and output of file. Before this topic, the information stored temporarily in the program will disappear as we close the program. However, now we can read from and write to files to get or store information. In this blog, I will explain classes and methods related to File I/O topic, and I will share a mini project I made using what I have learned about file I/O.

Stream Objects

A stream is an object that enables data to flow from the program to file or to I/O devices. When the data flow from the program to the file, the stream object is an output stream, as we write to the file. Contrasty, as data flow from the file to the program, the stream is an input stream.

Actually, we have already made use of input and output stream, when we use the following codes:

System.out.print("PrintToTheScreen");
Scanner input = new Scanner(System.in);

Text Files

Since we are reading and editing files, we should clarify that what we called “files” are usually text files. Different from binary files, which can be understand by computers, data in text files are encoded with ASCII coding scheme.

Dealing with text files, we need to import classes from java.io. As these codes show:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

Not only do we need the input and output stream classes, but also we need PrintWriter class to write to files.

The last line is used to deal with possible errors. We can use try catch to catch the error and send an error message.

try{
    inputStream = new Scanner(new FileInputStream("../example.txt"));
} catch(FileNotFoundException e){
    System.out.println("Failed to find the file.");
    System.exit(0);
}

This process is necessary for the program to run. The picture below shows what will happen if we do not deal with this possible error.

Picture1.png

Input Stream and Scanner

As this picture shows, we need to put the Scanner method in the try catch block. I have learned Scanner before, but we only used System.in, which is to get data from the keyboard. This time, we use the inputStream as the argument of the creation of the Scanner object. In side the parenthesis next to “Scanner,” we create a new file input stream. We put the name of the file there. The “../” means that the “example.txt” is located in the parent folder. If we use only “example.txt”, it will be in the same folder as the program.

Similar to what we have learned about Scanner, we can use methods like “.hasNext(), inputStream.next(), inputStream.nextLine(), inputStream.nextInt()”, etc. Every time we use .next…(), the Scanner will keep on searching, like a pointer, and it will never come back.

PrintWriter

For writing to files, we use FileOutputStream class as well as PrintWriter class which is used to write transmit data to the outputStream and to the file.

If we want to write to a txt file named “example” in the same folder of the program, we can use the following codes:

outputStream = new PrintWriter(new FileOutputStream("example.txt"));

This line is in the try catch block, before it, we need to declared the variable Output stream:

PrintWriter outputStream = null;

Then, we can write text to the file. Here is an example:

Picture3

This is quite similar to the System.out.print() method. We just need to change the former part to the PrintWriter object.

However, there might be a problem using the previous codes. If there is already a file named “example.txt,” this program will create a new file and replace the existing one, so the data in the original file will be deleted. If we want to append to a file, we can add a boolean argument into the parenthesis after “FileOutputStream”. Here’s the code:

Picture4

We put a another argument, “true,” after the file name, we can append to the file.

It’s important to note that after we finished using the input or output stream, we should close them, in another word, we clear the data stored temporarily in the streams. We use these codes (the two objects are created before):

 outputStream.close();
 inputStream.close();

Mini Project – Popular Names

After we learned file I/O topic, we did a mini project. That is, to write a program that can show the inputted name’s rank (according to popularity) and the number of people who are using the name. We are provided two files: One includes the boy names in the order of popularity and the number of people using them; the other is for girl names.

To create this program, I started using array, scanner, and input stream to store all the information in these two files.

4

Also, I used while loop and a int to access all the lines in the two files and write them to the array.

Then, I let the user to input the name, and then I used toLowerCase() method to make the problem more usable. I used subString() method to differentiate the names and the numbers. Then, I output them in a way that make sense. Also, I used a boolean variable to check if the name is found.

5

Here is the result:

3

This project shows my understanding and skill about file I/O. As what I said in the last post, I will continue on the Library project and implement file I/O. I believe the library project will be more easy to use after I used file I/O.

Smart Library Project

As mentioned in the last blog post, I finished this little project! This blog post will explain the features as well as some of the core ideas in this program.

The Class Diagram

Picture1.png

Here is the class diagram of my Smart Library Project. This time I finished both the Student class and Book class, as well as the main menu created in the Library class.

To interact in with the users, I used a main method in Library Class. I will talk through the menus and functions in the rest of my blog.

Terminal Window

5

As we call the main method, this window appears, and the main menu shows up. I did not write this menu in the main method, in fact, my main menu is very short. I did this by creating the menus in the library class.

This slideshow requires JavaScript.

Here is the class card of the three classes. For some methods, I made them private, since they are only going to be called with the class. For example, private methods that return student object and book object are very useful. Since the parameter is ID, you can input an ID and then the methods will return the actual objects. Then, we can use dot notation to call the methods of the Student class and Book class.

6

Here is the student menu. In this menu, we can add student, remove student, search students, which are functions that I discussed in my previous blog post.

7

This is also discussed in my previous blog post. Actually, the student class resembles the Book class. The difference is that there is an ArrayList in the Student class, which contains the books that one student borrows.

8

This is the Borrow/Return Menu, which I added a last. This is more difficult than the previous menus since it include borrow and return methods.

11.png

This is the most difficult method in this program. It firstly asks for the student ID to find the student. Then it brings the student’s book collection back to the book system. Since each book has an Unique ID, as the book object is returned, its ID will not change. The key of successfully creating this return method is that I created a return method also in the student class.

12.png

This method is in Student class. The difficulty of returning book is to remove the book from student’s collection and add the book back to the book system. Here, I pass a argument, which is the ArrayList textbook (the book system), into this method. Therefore, I can simply remove the book by “collection.remove(i).” The same method is applied to adding the book back to the book collection of the library.

Continue reading “Smart Library Project”

Track Class and Iterator

After we learned ArrayList class, we firstly reviewed while loop. Then we learned to improve our ArrayList by designing our own class as the type of the elements in the ArrayList, as the example of “Track Class” shown in the Textbook. Then, we learned Iterator, which will be explained later.

While Loop Exercises

Here are the exercises we have done to review while loop. After recalling the syntax of while loop, I found them easy. It’s also because we have created the program that print prime numbers last semester.

Picture1.png

Here are my codes.

1

While loop is different from for loop since the variable that stores the index is declared outside the loop. Also, “i++” is required to make the loop progress.

2

Also, sometimes we need to add addition variable to store the results coming from every time the loop runs.

3

4
4.33

 

The exercise is more complex, since it has a return type, boolean. In this exercise, there are two conditions, both of which determine if the input number is a prime number. At last, there is a return statement that returns the value stored in a boolean variable.

Library Project

The library program is a simulation of the program that the librarian uses to manage the books in a library. Now I have not complete the full program yet. Now, this program has the functions of adding, removing, and searching books. Here is the class diagram for the library program.

11

We can see that the class are connected by arrows. This means that classes use other classes’ objects or methods. I have finished the book class and library class, and here is a screenshot of the book class.

12

In this class, I created three fields. They are the name of the book object, as well as the ID. By using a static variable, I create a integer field that only belongs to the class. Therefore, if I use “bookUniqueID++,” every time an instance of the class is created, the ID changes. At the same time, since this variable is inherent to the class, I need to create a new field that belongs to each object created, which is the bookID variable. In this class, I created two accessor methods, which return the book’s name and ID respectively.

Before talking about the library class which is the centre of this program, I want to introduce the “Track Class” first.

Track Class

Here, the “Track Class” does not refer to a class inherent to the java utility package. Instead, it is a technique we can implement on ArrayList.

Here an example in the textbook:

26.png
Objects First with Java a Practical Introduction Using BlueJ (5th Edition);

Generally, using the “Track Class” is to firstly design our own class, and then use it as the type of the ArrayList. Therefore, the elements in the ArrayList is no longer String, but a series of objects, which can contain more information as well as more methods.

Here is how I implement it in my library project.

14

As I mentioned earlier, book is class I created for the actual books in a library. So how can we put them in a list and access their names and IDs? The answer is to use Book class type to declare a new ArrayList.

Continuing on Library …

22

In the library class, to make use of the Book class, I create a most basic method called “add book.” When it is called, it pass the argument to the parameter of the book object to create a new book object.

23
Remove book by ID

Here, I use a boolean “indicator” for a searching method. This means that the loop is trying to check if, in a loop, something meets a certain condition. If the bookID is found using “contain” method, the boolean indicator “contain” will become true, which is initially false. If anything is found, the program will not print our “No book matched.”

24

This is the beginning of the main method I used. I by printing of the menu and using Scanner, I can interact with users.

25

To let users choose the functions, I used switch loop. This is more efficient than write a lot of “ifs” and “else ifs.”

Iterator

We have learned that to scan through each item in an ArrayList, we have two methods. One is for-each loop, the other is while loop. However, there is another technique to go through an ArrayList – the Iterator. Comparing to while loop, the Iterator Object will replace the index of the while loop. By using the “.iterator” method of ArrayList (but we have to import the “java.util.Iterator” at first), we can create a more efficient loop.

27.png

This is an example of using Iterator. The method “.hasNext()” of Iterator class is similar to  the “hasNextLine()” method of Scanner class. The method “.next()” of the ArrayList will return the next item in the ArrayList. Iterator is like going through the ArrayList one by one, and it will not go back.

If we want to remove an object in the ArrayList, we can simply use –

books.remove();
//or IteratorObject.remove();

Remember there is not index in the parenthesis, since Iterator goes through the list by checking the only items themselves.

It’s advantage is that it can directly return the items in the ArrayList without index. Also, it can stop in the process, comparing to “for each” loop. However, sometimes it’s more convenient to store the index and use them later.

Continue reading “Track Class and Iterator”

Website Built with WordPress.com.

Up ↑