Welcome!
Long time no see! We have not written blogpost for quite a long time due to various factors. Recently, we started to think about IA, one of the most typical assessment in IB program. At first, I did not realize that CS IA was difficult and complicated. However, I changed my mind as I began to think about the topic of my IA. I have struggled with choosing an appropriate topic. I discussed with my teacher, Mr. Pete, for several times. Finally, I determined to do an application which could record student score and calculate students’ final scores. Pictures shown below are interview report and feasibility report.
Interview report is to help students customize the application. It also help students find the problem of the application and how to improve it. This is the interview report I did but it is only a practice one. So there might not be that perfect.
This is feasibility report for IA. Feasibility report helps students find whether their ideas are doable or not. My feasibility report is shown below.
Long time no see! These weeks we have continued to learn about JFrame class in Java Program. We know how to put buttons, selective buttons, and even pictures in a program.We also learnt how to change color and how to draw in Java Program. These add spices to our classes. It were a memorable weeks. We have learnt a lot during these weeks. Here are the things we have learnt during these two weeks.
Intro
First, there is an important concept in Java which is inheritance. The class at the top of hierarchies, superclasses, defines instance variables and methods common to all classes in the hierarchy. So subclasses inherits behavior and fields from superclasses.
Later, we learnt about GUI (graphical user interface). It makes the program more gorgeous. It enables user to enter data, display information, set program preferences (like color, fonts and so on)…
java.awt is the original components of java components. It hands off some of the display and behavior of the native windowing system. However, it has some disadvantages. One of them is that it is inconvenient in the look-and-feel of the various windowing systems. It is referred as heavyweight components. On the other hand, java.swing is the second generation of GUI components. It is referred to as lightweight components. Applications could run consistently.
Graphics Class and Paint Method
Graphics class enables users to draw pictures on the computer. It enables user to draw pictures with basic shapes. People could change the color of background and letters easily. The constructor of graphics class is different from any other programs we have written before. It is written like “public class ShellGraphicApp extends JFrame”, as shown below. It extends from JFrame, superclass. It uses the inheritance characteristic.
With the extension from JFrame class, users could draw, make the picture visible, change size, and even change colors. To be mentioned, the JFrame picture is originally invisible. So users need to remember to make the picture visible when utilizing JFrame. “draw…” method is to draw the outlined shape. “fill…” is to draw a solid shape which means that there is color in the shape. Please don’t forget that writing graphics code in paint method. There should be client class. If graphics application without client class, it is blank in the box.
Another thing needs to be mentioned is that graphics application is closely associated with coordinate system. The place where all shapes are drawn based coordinate system. Examples
Draw a line: g.drawLine(xStart, yStart, xEnd, yEnd);
Draw a rectangle: g.drawRect(x, y, width, height);
Next, it comes to colors. Before using color, it should be imported from the Color class from java.awt package. All drawings are done in current color which means that whenever users want to change color of a shape, line ,or filling color, users should change the color first. The default color is black. If users want to set the color in basic colors, it could be written as “g.setColor(Color.BLUE);”. If it is more complicated color, it should be written as “Color name = new Color (100, 211, 38);”. In order to draw a colored rectangle, programmer could write “g.fillRect(x, y, width, height);”. Then the rectangle will be filled with the current color.
Besides, we also learnt to draw ovals.
Draw an oval: g.drawOval(x, y, width, height);
Here is an easier method to move or resize an oval.
It is the same method to draw a circle.
We did a small activity to practice our skills.
Bar Chart
This is a program that we have done for assignments to review things we have learnt. It is related with GUI application. I hope you will like it.
GUI Application
GUI application helps computer become user-friendly and manipulative. As I have mentioned before, GUI extends from JFrame class. JFrame class is a Frame; it is a Window; it is a Container; it is a Component; it is an Object. It means that JFrame inherits all those characteristics. There is an enormous library of methods inherited. Below is the steps used to create GUI application.
The first step is to call the constructor of JFrame superclass: “super(“GUI Intro”);”. Then, get an object reference to the content pane container. “contents = getContentPane( );”. We need add all components into the content pane. By this way, those things would be shown. Next step is to set the layout manager. “contents.setLayout(new FlowLayout( ) ); ”. It is the rule. Layout managers could help arrange the GUI components in the window. During the class, Mr. Pete showed us the result without setting the layout manager. Some texts, or shapes disappeared. Instantiating each component is the next step. For example, “labelName = new JLabel(“I am Eva. ”); ”. Then the user need to add each component to the content pane. “contents.add(labelName);”. The user could set the size of the window, which is “setSize(300, 500); ”. The last step is to make the window visible, which is written as “setVisible(true);”.
In order to practice GUI application, we did a small activity. It is shown below.
We can also add event and event handler. By writing if-else statement, event handler could identify which component fired the event. When we write the actions, we need to use the word “implements”. We played with JButton during the class. The event handler uses the “getSource” method to determine which button was pressed. JTextField provides opportunities for user to type in the box, which increases the reactions between programs and users. JLabel is used to label the textfields. To be more complicated, we learnt radioButton. This method makes the buttons become selective.
private class SCHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Write the code of actions
}
}
To be more familiar with these functions, we wrote a program, simple calculator. It has the same function as calculators which could do the simple calculations.
Overall, we have learnt a lot of stuff during these classes. I am really looking forward to the next week. I hope that I could learn more things related with JFrame. Simple calculator is the first program that I feel I am a real programmer. I believe that practice makes perfect. I could do better in the future class. I believe I will enjoy the classes!
Today is the first day of our group 4 Project. At the beginning, we had brainstorms. We wrote down all thoughts of myths we had on the whiteboard. Finally we chose our research question as that what is the correlation between apple skin color and the sweetness. Then we begun to write the flow chart of our experiment. After writing the basic scientific method, we discussed with different teachers and updated the experimental method. The picture shown below is the final flow chart of experimental method.
Even though we have not begun our research, we can assume the implications of our investigation. It might not be really useful in computer science field. The photoshop method we use to measure the color could be an photoshop example in computer science field. However, it is of extreme use in people’s daily life. It could help consumers to select sweet apples. By this way, consumers could buy the apples they like. The method might be applied to people all over world who purchase the same species of apple because I am not sure whether the result could be useful for the other species of apples.
My group mates are Chloe, Kate, and Turvey. I feel all of my group mates are hardworking and creative. During the brainstorm part, all of us contributed their thoughts. I am computer science student, so I could draw the flowchart and use computational to make sure the logics. Chloe, as a Physics student, could use her physics knowledge to measure the color of apples. Turvey, as a Chemistry student, mainly focuses on the measurement of sweetness. Kate, as a Biology student, could select apples. All of us can peel apples and juice apples.
Of course, there were possible conflicts when choosing the research question. Nevertheless, we did not have quarrels. We discussed together and provided the opinions why the student agreed with the idea and why they did not. We listened to each other opinion carefully and finally we could reach an agreement. I believe we could resolve conflicts in the same way in the future.
I believe we will have a precious memory and memorable experience. I really look forward to the group 4 project.
This semester we learnt more about how to use array in OOP. Last week, we learnt about the collection in pseudocode. This week, we began to study collection in Java, which is called ArrayList Collection. We also learnt about some characteristics and functions of ArrayList. Learning theories or definitions and doing small projects were at the same time for the last week classes. We had a wonderful week of Computer Science.
ArrayList & Collection
Collection is an unordered list of data, which is like a resizable array. It keeps a private count. The most magical function is that it keeps the objects in order automatically. In other words, if user delete or add an item in the middle of the collection, the list will keep in order automatically. There are two types of collection which are generic collection and non-generic collection. The difference between the two types is that generic collection can only hold the same type of data, while non-generic collection can hold different type of data. One benefit of collection is that it is an efficient RAM because it could be as big as people need. There are the several operations of collection.
Name
Function
.addItem(new data item)
Users want to add another item in a collection
.getNext()
Get next item in the list
.resetNext()
Go back to the beginning of the list 【index = 0】
.hasNext()
Check whether there are items at the next index
.isEmpty( )
check whether the collection is empty or not
ArrayList is the implementation of collection in Java. There is no limit to the number of files. ArrayList has many class libraries. These class libraries make ArrayList have more functions. ArrayList class is in the package — “java.util”. By writing “import java.util.ArrayList;”, these functions of ArrayList could be utilized. There are several characteristics of ArrayList. Items could be added and removed. Each item has index, which is same as Array, starting from 0,1,2,…. It keeps the order of objects automatically. If an item is removed, the indexes of other items could change.
Name
Function
collectionName = new ArrayList<DataType>( );
e.g. files = new ArrayList< >( );
Initialization (diamond notation)
collectionName.add( DataName );
e.g. files.add(filename);
Add a file to a collection
collectionName.size( );
e.g. files.size( );
Return the number of items in a collection
collectionName.remove(index);
e.g files.remove(index);
Remove an item from a collection
collectionName.get(index);
e.g. files.get(index);
Get the information of an item in a collection of a particular index
We also learnt about for-each loop in this week classes. It allows iteration over a whole collection. With an for-each loop, each item could be displayed in the loop for exactly once. The advantage is that for-each loop is easier to write compared with for-loop, or while-loop. However, the disadvantage is that programmers could not stop the loop at the middle.
Besides, we studied more advanced match, kind of search. There are two kinds of String match: partial match and exact match. Partial match is if part of the item in a ArrayList has the String, it make sense. Exact match means that the item must be the same as the String.
Of course, there are other types of functions not shown on the table above. You could go to the website to find more useful information.
Static fields, methods
Data of Static fields, methods and static constants could only be shared belonging to the class class, but not to the actual objects. When users call it, users should use the dot syntax with the class name instead of object reference as shown below.
ClassName.methodName( argument list);
ClassName.staticDataName
Wrapper Classes
Wrapper classes mean that “wrap” primitive data type, (like int, float, double and so on), into an object. It is quite useful when methods require an object argument. It could also convert String into an int or double. There are two classifications: autoboxing and unboxing. Autoboxing is used when primitive data type is used where an object is expected. It could automatically convert primitive data type to a wrapper object. (Integer intObject = 100;) While, unboxing is used when an object is used where primitive data type is expected which means to convert a wrapper object into a primitive data type automatically. (int aHundred = intObject;)
Here are methods
Return
Argument list
Function
int
parseInt(String s);
Returns string s into a int — primitive data type
Integer
ValueOf (String s);
Returns string s as an Integer object
double
parseDouble(String s)
Returns string s as a double
Double
valueOf(String s )
Returns string s as a Double object
We did an exercise to practice wrapper classes.
System Class
System class is in java.lang package which means that it does not need to be imported on the top of the program. For example, input devices and output devices. It not only represents the standard input device, but also represents the standard output device.
For example
Scanner sc = new Scanner (System.in);
System.out.println(“Hi Eva! Welcome to the world of Computer Science! ”);
There is a special use of system class that we have learnt in this semester which is the static exit. It is relatively useful when users want to stop execution at a place which is not the normal exit.
System.exit(0);
toString Method
The return type of toString method is String. It is utilized to converts the object data to a string. All classes have toString method. Another thing worth to be mentioned is that toString method is called automatically when an object reference is used with print and println methods.
During the class, we did a program to practice toString method.
Math Class
The function of Math Class could be guessed from the name. It offers static constants and static methods in order to perform common calculations in Java. It is also in the java.lang package. In other word, it does not need to be imported. In order to explain static constants in Math Class, I could give two examples to help understanding.
For instance,
PI — the value of pi which is 3.1415926535…
E — the base of natural logarithm
System.out.println( Math.PI );
System.out.println( Math.E );
There are also various methods in Math Class. All these methods are static.
All in all, we did a practice for Math Class which is shown below.
Programming Activities
This week, we also did a lot of activities during the classes and after classes. We first did a music organizers exercises in order to be familiar with the basic knowledge or information of ArrayList.
For some objective reasons, we could not always practice collection pseudocode on electronic devices. So we often practiced by writing on the papers. These are the pseudocode I had written in order to practice and learn. Other java programming activities are all shown above. Hope you enjoy it!
Conclusion
In a nutshell, we learnt a lot during this week, especially of ArrayList and collection. We got a deeper understanding of static method, fields, and static constants. By learning wrapper classes, toString methods, math class, and system class, I felt really satisfied. I am looking forward to the next week! I believe I will enjoy the later classes!
This week we have done a mini project in groups. Jamie and I are finally in a group and we chose Project C. The main purpose of the project is to encapsulate the concept of grades on a test and assume that students grade are composed of a list of integers between 0 and 100. According to the question, the title of should be “test” and object inside test are grades of different tests. Then we create another class called “client”, which is used to run or test the methods. As the question has required “all grades can be randomly generated”, we need to import Random from Java predefined method first.
First of all, we created a constructor with only one parameter, which is the number of students. Then we created a new integer array and assigned the size of the array. We wrote a for-loop to assign random numbers to the array.
Then we wrote an accessor method to return the grade at designated index and a mutator which could set new grade to a designated index.
The first method we wrote a toString method which was to put the array to a String. Firstly, we created a new String called temp. Secondly, by running for-loop,we put the grade each index one by one into the new String, temp. Finally, we return the String temp.
The second method is equaled method. The parameter was two integers which represented the two indexes of grades users want to check whether they are equal or not. We create a boolean called result. Then we used an if-else statement to check. Finally, we return the boolean result.
The purpose of the third method is to do ascending sort by using bubble sort. Finally, it returns the ascending array.
The fourth method is to find mode, which means that the program is going to find numbers which occur in the list most frequent. We created a new array called counter which is used to find how many times a grade has occurred in the array. Then we created a new integer called max. In a for-loop, we found the maximum number in an array. At last, we return the integer in the array grades with the same index of max.
The fifth method is to find the median. Firstly, we sorted array grades in ascending order. The meaning of median is the value separating the higher half from the lower half of a data sample. So we could definitely return the number in the middle of the array.
The sixth method is to find the highest score of the test. First, we used bubble sort to form an ascending array. Then we return the grade with the largest index in grades.
The last method is to find the average score of the test. To be more accurate, we set average as primitive data type double. We add all grades in the test and divide the sum by the number of students. Then we return the average score.
Finally, we tested the program with the client. At first, there were some errors. We tried hard to debug these problems. At first, our program is not user-friendly. Then Mr. Pete suggested us to add more connections with users. Then we changed our program and we let users to input value of parameters by themselves. We eventually succeeded. Our satisfactions were fulfilled at that moment.
Through the mini-project, I have learned that we need to read the question carefully because there might be some hidden messages in the question. For example, at first, we set the class name as “MiniProjectC”. After Mr. Peter’s warning, we found that the main method should be called “test”, which is a hidden message in the question “encapsulate the concept of grades on a test”. Of course, there were frictions between Jamie and me, but both of us learned from the frictions. In this mini-program, I found that it was not a simple task when writing the code. I really enjoyed the process. I am looking forward to the next week!
Long time no see! Time flies. It is nearly the end of the year. We have learnt a lot of things during this semester. Even though we only have three classes per week, we work hard to learn more stuff during the class and after class. We start to learn more advanced things Java which is object oriented programming.
Object Oriented Programming paradigm
Before discussing this topic, we need to understand what programming paradigms are. Programming paradigms are a way to classify programming languages based on their features. In other words, programming paradigms are various means to solve a problem. As we all know, there are many roads to one destination. Programming paradigms are just like the roads and the result is the destination. A programming paradigm does not refer to a specific language but rather to a way to program, a methodology. There are two types of programming paradigms which are imperative programming and declarative programming. We mainly focus on imperative programming these weeks. Imperative programming tells the computer how to do and what to do. Imperative programming is the most adaptable when it comes to implementing other paradigms. Procedural programming and object-oriented programming are imperative programmings.
Procedural programming simply contains a series of computational steps to be carried out. It is about writing a list of instructions to tell the computer what to do step by step. It relies on procedures or routines. While object oriented programming contains data and behavior into objects. It could be used for many objects. Another important aspect of OOP are classes. A class can be considered as a blueprint for an object.
Members of Object, Class, and Methods
There are some key terms of OOP for people to remember: object, class, and method. The most significant concept is object because OOP is formed based on objects. There are three key characteristics of an object which are attributes, identity, and behaviors. Identity is the identifiers in Java Program. Attributes show the characteristics of an object, like color, size ,and so on. It describes the state of an object. While behaviors mean that what can an object do, what is the function of an object. It also means the methods of an object.
Class can be referred as a blueprint for an object. Your cat is an instance of the class of cat. Class usually is a template to create specific object. There are many data of a program. Classes permit people to separate the data for each object. At the same time, people could use common code to control them. However class could not be executed directly, it need to be instantiated which means to create an instance in the form of object.
Each object has fields (state) and methods (behavior). For example, an object could be a cat. The cat would have color, name, and size, and breed. These are the fields of the object. It is any primitive data type which stores value of an object. Fields are variable defined in the class. At the same time, the cat should know how to eat, how to walk, and how to sleep. These are the methods, also behaviors, of the object. The fields of an object are independent to each other. Methods will be written in code to manipulate the object.
Classifications methods
There are different methods of OOP which are constructors, accessors, utility, and mutator. Constructors are responsible for set up properties of an object which mean to store the value of the object when it once be produced. It does not have a return type. Accessor method is ‘get’ method which means to return the current value of the object data. Return type is written just before the method name. Mutator method is to reset the value of an object data which means to change the values of the object data. Utility is all other methods except constructors, accessors, and mutators.
Conclusion
We have learnt a lot of things during these weeks. Before it, I have never thought that Java program would have this advanced function that it could create objects by ourselves. I get a basic idea of what OOP is, and how it works. But I am still a beginners of OOP.I am looking forward for the following stuff. I believe I will discover more fun things in the later classes.
We have not seen for one week. This week we still focused on Java programming. We learnt four type basic computer algorithms which were sequential search, binary search, bubble sort, and selection sort. These were amazing and magical. I have fun during last week. Now let’s see what we have done during last week.
Sequential Search
In computer science, linear search or sequential search is a method for finding an element within a list. Sequential search is the most rudimental way to search an object. Usually it begins at the first item in the list. It checks each item of the list one by one until a match is found or the whole list has been searched. The worse run in a sequential search is that the computer check the list with n items for n times.
Pseudocode
Java Program
Binary Search
This computational algorithms is more convenient compared with sequential search. It saves time especially when the index of the array is significantly large. Binary search works in sorted array which means that the array should begin from the smallest to the largest. The computer compares the target value with the value of the medium item in the array. If they are equal, the loop ends. If they are not equal, there are two consequences. If the target value is greater than the medium value, the part smaller than the medium value is abandoned. The comparison process will begin again which means to compare the target value with the value of the medium item in the new sequence. The process continues until the target value is found or the first value is greater than the final value. On the other hand, if the target value is smaller than the target value, the computer will abandon the part that is greater than the value of the medium item. The comparison process will begin again which means to compare the target value with the value of the medium item in the new sequence. The process continues until the target value is found or the first value is greater than the final value. As a result, binary search seems to be more intelligent compared with sequential search.
Pseudocode
Java Program
Bubble Sort
Bubble sort is the simplest sorting algorithm that works by swapping the adjacent item if they are in the wrong order. Supposing that we are going to do an ascending sort, the first number is compared with the second number. If first number greater than the second number, first number is swapped with the second number. Then we compare the second number with the third number. If they are in the wrong order, we swap them. If not, the sequence do not change. We continue the procedures until there is no swap occurred from the first number to the last number. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. However bubbles sort is extremely slow when meets the large size of list.
Pseudocode
Java Program
Mr. Pete has taught us two methods to do bubble sort. One is to use two for-loops, while another one is to use one for-loop which is more simple compared with the first one. The improved bubble sort is successful by utilizing the combination of boolean sign “swap” and while loop.
Improved Bubble Sort
Selection Sort
The selection sort seems as an advanced version of bubble sort. It is improved from bubble sort by making only one swap for every pass through the list. Selection sort’s simplicity is known to people, however it is still inefficient on lists with large amount of items. Selection sort divides the whole list into two lists. Sublist of items has already been sorted, while another sublist of items has not been sorted. Initially sorted sublist is empty, while unsorted sublist is full which means that all items are not in sorted sequence at first.In first pass, the computer finds the smallest item in the array. Then the computer swaps the smallest number with the number placed at the very left (assuming that it is an ascending sorted, the array is read from left to the right). Then the very left number is in the sorted sublist. In the second pass, the computer finds the second smallest item in the array and swaps the second smallest number with the number placed at the very left in the unsorted sublist. The procedure is continued until unsorted sublist is empty. You could better understand the selection sort by looking at the below image. Similarly to bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place.
Pseudocode
Java Program
Homework
This assignment is to let the user to type the ID number and the relevant words will be printed out by using binary search.
This is an assignment related to bubble sort. Mr. Pete let us to let user to choose the way to sort which means that the user could choose to let the array do ascending sort or descending sort.
Conclusion
We have done a lot last week. Even though we used a whole class on Thursday to debug which was boring, we learnt at least something. I knew that debug is the most important and necessary part in studying of programming. We have learnt how to write java program of linear search, binary search, bubble sort and selection sort. I am looking forward to learning amazing new stuffs in the next week! See you!
Welcome!
Time flies, it is almost the end of November. We have learnt a lot even in Java programming. All of us grew a lot. We began to write more complicated program. Even though those programs were significantly easy according to professional programmer, we are satisfied at what we have done and our progress. We learnt the use of various loops (for loop, while loop, and do-while loop), one-dimensional array. We also did a lot of activities in class and after class.
Programming Exercise 1
This is a program to calculate the possible adult height of a child. It is designed to calculate female and male differently with different formula. In this program, I utilized do-while loop. Do-while loop is loop after completing the instructions a time. It promises that the program will at least do one time of the instructions. In this program, I also use a technique to quit the program. When the user prints out “Y”, the program will exit.
This slideshow requires JavaScript.
Type Casting
We have learnt two kinds of type casting which are implicit typing cast and explicit typing cast. Implicit conversions do not require any operator for converted. They are automatically performed when a value is copied to a compatible type in the program. In other words, when two types of data are compatible, java program will automatically convert one type to another type of data.
When they are not automatically performed when a value is copied to a compatible type in the program. It is called explicit conversions. If the calculations is in the parenthesis “(total/num)”, explicit cast type is done after the calculation. It is known to us all that people should do the calculations in parenthesis first. In this case “(double) total/num”, the program explicits total first then do the calculations. Different java program will lead to different result. Please loop at the figure below to have a better interpretation.
Syntax — (datatype)(expression)
3 out of 4 programming exercise
These four exercises are designed for practicing for-loop. For loop is used when programmers know exactly how many times the statement will be repeated. The standard request is shown below. I chose the second, third, and fourth one among these four exercises.
for (initialization; condition; iteration)
{
Statement
}
The second exercise is to print out all prime numbers between 2 and 100. I also utilized while loop inside the for loop. While loop is that the code in the parenthesis will be continued to be implemented until the condition at the beginning is not established anymore.
while(condition)
{
Statement
}
This is a program that utilizes while loop
The third exercise is to print out all the multiples from 3 to 36. It is quite easy compared to the second one. I only used on for loop to get the final results.
The fourth exercise is to output 10 lines of numbers, with 1 number in the first line, 2 numbers in the second line and so on. I used nest loop to get the final result. The first for loop is to count the number of lines. The second of for loop is to count the numbers in each line as images shown below.
In this week, we also learnt shortcut arithmetic operators which make our life more convenient. We learnt “++” and “- -” which meant increment by 1 and decrement by 1 separately. When people write programs, it is more easier to use short arithmetic operators. I believe there are more shortcut arithmetic operators waiting for me to discover and to learn. I hope I could learn more in the future class.
The need for the use of array
Array is an important thing we learnt these weeks. When we learnt array in pseudocode at the beginning of the semester, Mr. Pete has mentioned to us that this part will occur in the future study of Java. An array is a container object that holds a fixed number of values of a single data type. In my opinion, the design of array is really intelligent in Java program due to the fact that arrays are always used in not only in mathematics, but even in our daily life. Array could be used in various areas, like statistics, mathematics, computer science and so on. The length of the array is established when the array is created. The length of the array shown below is five. Each item in an array is called element, like “2” “6” “3” “7” “4” are items in the “numbers” array. Each element could be represented by a numerical index. However, the index is counted from 0. For example, numbers[0] represents the first integer in the array which is “2”; numbers[3] represents “7” and so on.
int [ ] numbers = {2,6,3,7,4}
Arrays are object. So there are two rules when creating an array. The first step is to declare a reference to the array, like I declare the above integer array as “numbers”. A reference to an array is like the “name” of the array. When the programmer want to use the array later, they could just mention the reference to this array which is more convenient. The reference to an array should follow the rules in naming section in last blogpost.
Syntax: datatype [ ] arrayName;
Example: double [ ] faceValue;
The second step is to instantiate an array which means that to regulate the array length.
Syntax: arrayName = new datatype [size];
Example: faceValue = new double [6];
People could combine the first step and second step together.
Syntax: datatype [ ] arrayName = new datatype [size];
Example: double [ ] faceValue = new double [6];
Array Exercises
After learning the usage of array, we combine the use of loop with array. We did a program to output the maximum and minimum number the user has inputed. First I clarified all variables. Then I established a for loop to record the numbers user has inputed. We set ‘max’ and ‘min’ variable with the value of the first number in the array. We compare the first number with the second number. If the first number is greater, ‘min = arrayName[1]’. If the second number is greater, ‘max = arrayName[1]’. The program is shown below and there are descriptions and comments on it.
Another exercise of array we have done is grade array. We first calculated the average score of a class, then we found the highest score and lowest score in the class. I let the user to input the number of students in the class and then enter the grades of students separately. In this program, user could choose to do it many times. If the user inputs a number greater than 100, the program will ask the user to enter the grade again. By utilizing loop and array, I eventually get the final result successfully. However the program is too long to have screenshot in only one image. I divide it into three images. You could look the program and the result below.
This slideshow requires JavaScript.
Exercises
Besides exercises that I have mentioned above, we also did other exercises. We did while loop exercise. The most interesting program I have written is the guessing game which is also a program we wrote during this time.
Loop exercise 1 is to let user choose to print odd number or even number to a particular number set by the user.
This slideshow requires JavaScript.
Loop exercise 5 is calculating the average grade of students in the classroom.
This slideshow requires JavaScript.
Guessing game program will ask the user to enter a number between 0 and 10. After that it will check to see that the number is equal to a random magic number. If the user guesses it right then he/she will win the game, if not the user will have to try again.
This slideshow requires JavaScript.
Conclusion
These weeks we learnt more stuff in Java programming — loops and arrays. In my opinion, both arrays and loops are extremely useful in Java program. Many daily life situations could be solved by applying these two techniques. From those activities and exercises, I am accustomed to the usage of array and loop. These are happy experience and memory. I am looking forward to the future study in Java program. Be constructive and positive!
This is the last week of October brought us surprise. We finally began to learn Java stuff. It is an exciting week because we have first contacted with programming. This week Mr. Pete mainly introduced java to us. We get a basic knowledge of Java: rules in Java and we created quite a lot of Java programs.
Intro to Java
Java is a high-level programming language and a cross platform. Java program should be written strictly. All source code is first written in plain text files ending with the .java extension. These files are then compiled into .class files by the java compiler.
General Steps of Creating a Java Program
In order to create a Java program, we need first to know the general steps of creating a Java program. First, we should create a new class and create a new name. It is necessary to mention that class name should not have space. After opening the class, we delete all the yellow part. On the top part (green background), we should write the description for this program which is convenient for people to know what the program is about.
Through computational thinking, we will know what problem is. Then we identify what data do we already know. We will identify other data we will need. After finding the unknown data, we declare variable names for those unknown data.
Next, we initialize the value of any possible identifiers (eg. int numA = 1).
Later, we perform our calculations, like doing the mathematical things(writing the equations to calculate the result).
Eventually, we output or print the result (System.out.println();)
These are the abstract steps for creating a new Java program.
Java’s Primitive Data Types
There are eight primitive data types: byte, short, int, long, float, double, boolean, char. Different primitive data types have various meanings.
“byte” is an 8-bit signed two’s complement integer. The minimum value of byte data is -128 and the maximum value of a byte data is 127. The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. Byte is so useful that can help people to save memory.
“short” is a 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767. People can use a short to save memory in large arrays, in situations where the memory savings actually matters.
“int” is a 32-bit signed two’s complement integer. We use “int” a lot during Java programming.
“long” is a 64-bit two’s complement integer. The signed long has a minimum value of -2^63and a maximum value of 2^63-1. Use this data type when you need a range of values wider than those provided by int.
“float” is a single-precision 32-bit IEEE 754 floating point. This is not the main topic in IB program. So we did not discuss a lot during the class.
“double” is a double-precision 64-bit IEEE 754 floating point. Double could represent an extremely large range of number. For decimal values, this data type is generally the default choice. However this data type should never be used for precise values, such as currency.
“boolean” has only two possible values which are true and false.
“char” is a single 16-bit Unicode character which means that it could represent characters, like Chinese characters, English characters.
Java operators and arithmetic operators precedence
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups :Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators, Assignment Operators, Misc Operators. We mainly focused on arithmetic operators which are really useful in basic Java programming.
Let’s assume that integer variable A holds 10 and variable B holds 20.
Operator
Description
Example
+ (Addition)
Adds values on either side of the operator
A + B = 30
– (Subtraction)
Subtracts right-hand operand from left-hand operand
B – A is 10
* (Multiplication)
Multiplies values on either side of the operator
A* B is 200
/ (Division)
Divides left-hand operand by right-hand operand
B / A is 2
%(Modulus)
Divides left-hand operand by right-hand operand and returns remainder.
B % A will give 0
++ (Increment )
Increases the values of operand by 1
A++ gives 11
– – (Decrement )
Decreases the value of operand by 1
B – – gives 19
When people calculate the arithmetic sentences. “()”comes first, then it should be “*” “/”. After doing multiplication and division, it should do addition and subtraction “+” “-“. Finally it comes to “=” to get the final result.
Screenshots of java exercises (code and output)
This is the first program we wrote which was an application to show “Hello world! My name is …”Actually it is really simple but I am really excited because this is the first program I have written in this semester. We know that we MUST write “public static void main(String[] args)” before every program. Maybe because it is difficult to understand for first programmer. So Mr. Pete did not explain what did it mean.
This is the second program which could calculate the area of a circle with particular radius.
This is the first long program we wrote which has arithmetic function. In this program, users could input their individual values. In order to make it come true, we entered “import java.util.Scanner;” on the top of the program. You could see it from the picture shown below.
We use “if” clause to judge the parity of a value and then print out the result.
Conclusion
We learnt a lot during this week. I am so exciting that I eventually began to learn Java program. We created a LARGE amount of programs during the first week. The feeling is amazing. Besides how to create a java program, we also learnt about the basic knowledge of Java program and the basic rules for Java programming. I am looking forward to the next week.
This is the seventh week of this semester. We learnt algorithm, pseudocode and flowchart this week. Even though we have learnt these in last academic year, there are still new stuff and something we have forgotten. We tried to solve more difficult problem in less steps during the classes in this week. We also did a lot of interesting activities. It is an exciting week.
Define Algorithm
We first reviewed knowledge associated with algorithm. Algorithm is a set of step-by-step clear instructions to solve a problem. Algorithms can perform calculation, data processing and automated reasoning tasks. Even though is seems that algorithms only involves in science, actually it is everywhere in people’s daily life.
Properties and Expressions of Algorithm
Algorithms have several properties which are finiteness, definiteness, input, out and effectiveness. To be finiteness means that an algorithm can be expressed within a finite number of steps and it could terminate after particular number of steps. Algorithm is definiteness because an algorithm should be written in well-defined formal language which does not lead to misunderstanding of the steps. Algorithm must have inputs which means that quantities must be entered before the algorithm begins. Out means that an algorithm should have an output associated with inputs when an algorithm ends. To be an effective method, all instructions in an algorithm should be exactly be done by processor in principle and it could be accomplished in a finite amount of time and space.
There are several expressions of algorithm: natural language, flowchart, pseudocode, and programming language. Natural language is simple English which is somehow verbose and ambiguous. We all know that language might cause misunderstandings in daily life.
PseudocodeProgramming Language
Flow chart is a type of diagram as a representative of algorithm which illustrates a solution model of a given problem. It shows the steps in various types of boxes which are connected with arrows. Pseudocode and flowchart can be transformed from each other. Pseudocode, informal language, is generic artificial language intended for human to read rather than computers. Programming language is a formal language intended for computers to understand and process it which comprises a set of instructions used to produce various kinds of output, like Python, Java and C++.
Decision Making Process
There is a process for decision making in algorithms. It could be concluded in four steps which are identification, development, selection, and implementation. Identification means to identify what problem is, to understand the problem, and to formulate the problem. Development means to discover different alternatives (methods) to solve the problem. Selection is to choose the best alternative in order to solve the problem. The last step, implementation, is executing the selected solution to find that whether the selected solution could actually solve the problem. If there is any problem, it should go back to redo the previous step. If there is no solution for the problem, people should go back to the first step, identification, to identify the problem again. If the most effective way could not be found which means that there might be some mistakes in development, development should be done again. If program does not work by utilizing the selected solution, selection should be done again.
Proper Pseudocode Notations and Conventions
Pseudocode involves a series of English-like statement. Pseudocode is like a planning tool. It is often written before designing the flow of a program. There are some common pseudocode notations. “Input” refers that users will enter something. It might be numbers, letters, or even sentences. “Output” means that an output will appear by operating the algorithm. The output could be printed or shown on the screen. “While” is used when there is a loop in algorithms which means that several instructions would be repeated for several times until it satisfies the condition. “While” is often written with the condition of the loop. “For” means a counting loop. “If-then-else” is used when there is a choice needed to make. “Repeat-Until” infers a loop with a condition at the end of the loop.
Division (quotient) vs. Modulus (remainder )
Dividend
Divisor
Quotient
Remainder
16 Div 3 == 5
16
3
5
1
16 Mod 3 == 1
16
3
5
1
Example of “For”
Let N=0
For each person in room
Set N=N+1
There are also conventions for pseudocode. Variables name should all be capitals, for example a user inputs a number, the variable could be “NUM A”. A significant rule is how “=” is used. “A = 7” means assigning 7 to A. “A == 7” indicates A equals to 7. We also learnt how to write numbers in sequence which is much more convenient when dealing with a sequence of numbers.NS=[3,5,2,36,14] (Array) NS[0] = 3; NS[3]= 36 ; NS[2]= 2. It should be written in “dot notation” (Java, C++ and so on). Pseudocode keywords should be written in lower case, for instance “loop”, “while”. Method name is mixed, like “getRecord”. Output could mean that data is printed by a printer or is shown on the screen. If “//” appears, behind “//” is the explanation or comment for the pseudocode written before “//”.
We have done some activities to practice pseudocode. These are activities we have done. We strictly followed the decision making process: identification, development, selection, and implementation.
This slideshow requires JavaScript.
This slideshow requires JavaScript.
We also tried to translate assembly language to pseudocode. Last week, we had an assignment which is to use LMC to do multiplication. This week we used the assembly language we wrote in LMC and translated to pseudocode. Here is the picture of the activities.
Steps of Creating a Trace Table
Trace table is the new stuff we learnt in this semester. Trace table is a tactic to test algorithms to make sure there is no logical errors. It can also be used to record outcomes of an algorithm. I used the following pseudocode as an example to show how to create a trace table.
First, write down all variables in the first line.
COUNT
N
SUM
N div 2
N mod COUNT == 0
SUM = N
Output
Second, filling the initial value provided in the question in the second line of the chart
COUNT
N
SUM
N div 2
N mod COUNT == 0
SUM = N
Output
6
0
3
Third, input all loop values (in this case, it is variable — COUNT) vertically in the “COUNT” column.
COUNT
N
SUM
N div 2
N mod COUNT == 0
SUM = N
Output
6
0
3
1
2
3
Fourth, follow the each pseudocode statement and fill the respective results in the cell for every change.
COUNT
N
SUM
N div 2
N mod COUNT == 0
SUM = N
Output
6
0
3
1
1
T
2
3
T
3
6
T
T
Finally, write down the final output.
COUNT
N
SUM
N div 2
N mod COUNT == 0
SUM = N
Output
6
0
3
1
1
T
2
3
T
3
6
T
T
Perfect
As shown above, it is a step-by-step example of how to establish a trace table. Trace table is truly imperative for checking whether there are logical errors or not, but also it could help people to find the result of a pseudocode.
First, we followed ,our teacher, Mr. Pete’s steps to make the trace table of his pseudocode for example 6. Here is the picture of Mr. Pete’s pseudocode for example 6 and my trace table. We also practiced how to make a trace table during the class. We checked each other’s pseudocode’s logic by utilizing trace table which is extremely useful. Here is the picture of our on-class activities.
This slideshow requires JavaScript.
Battleships game activity
Battleships game activity is a really interesting activity. There are 26 ships on the paper and each ship represents a different alphabet letter and a code. We did these activities in pairs. One student held a sheet of 1A, while another student held a sheet of 1B. First, every student circle a ship on the their own paper. Each student should try to locate their group mate’s ship. StudentA says the guessing letter of studentB’s ship. If it is right, the studentB should tell studentA that it is right. If it is wrong, studentB should tell the code of the letter studentA is guessing. StudentA writes down the code. We did two activities to discover the algorithms of searching an array of numbers. Afraid of not understanding the rule of the game, I copied a more clear instruction written by Mr. Pete.
In first activity, we are given a paper of ships with random codes. In the second activity, we are given a paper of ships with codes from smallest to the largest. The rule changes a little. After circling the letter, each student should tell the partner the code of the circling letter. If the letter is wrong, the partner could tell the student the code of guessing letter. So students are more easier to find the right answer because they have a relative small range of the letter. In the last activity of battleship game, students did not tell the code of circling letter to each other, but they will say whether the code is larger or smaller.
This activity highlights the algorithms of searching an array of numbers. With letters arranged according to numbers, it is much easier for students to guess and it saves time. In the last activity, student could most use five times to guess the right letter. However, in the first activity, it depends on fate. Mark and I were a pair. But I did not win even one game when playing with random numbers. Even once, I did not find the right letter, until I guessed 26 times (so sad). BUT it is an extremely fun activity we have done during last week.
In the first activity, it applies linear search algorithm. As you can see, the linear search algorithm is nothing else then looping though all element of the array and compare the element with the number we are looking for. If we find the number we set before and then we break out of the loop. In the second activity, it applies binary search algorithm. It finds the position of a target value within a sorted array. Binary search compares the target value to the middle number of the array. If they are not equal, the half in which the target cannot lie is eliminated, and then the binary search is repeated on the remaining half. The process does not stop until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Compared with linear search algorithm, binary search algorithm is more convenient in most of the time.
Activities
Besides those activities described above, we also did some other activities in LMC. We made LMC code for the following questions in the video.
This slideshow requires JavaScript.
Due to limited time, we did flowchart practice after class. It is known to us all that flowchart and pseudocode could be convert from each other. So we wrote flowcharts for example 3-7, according to the pseudocode.
This slideshow requires JavaScript.
Conclusion
In conclusion, we learnt a lot and did a lot and did many activities. It was a fulfilling week. We reviewed algorithms, pseudocode and flowchart. We created more difficult pseudocode this semester. We also learnt how to create trace table to check for logical errors. By playing battleship game activity, we learnt the significance of linear search algorithm and binary search algorithm. I am looking forward to the computer science class in the next week!