If there is one prayer that you should pray/sing every day and every hour, it is the
LORD's prayer (Our FATHER in Heaven prayer)
- Samuel Dominic Chukwuemeka
It is the most powerful prayer.
A pure heart, a clean mind, and a clear conscience is necessary for it.
For in GOD we live, and move, and have our being.
- Acts 17:28
The Joy of a Teacher is the Success of his Students.
- Samuel Dominic Chukwuemeka
I greet you this day,
For My Students, please do the following:
First: Download and install the NetBeans Integrated Development Environment (IDE), or any suitable IDE for Java.
Second: Review the required readings for each module including the Student-Teacher scenarios.
Third: Review the recommended readings for each module.
Fourth: Review the recommended videos and textbooks for each module.
Fifth: Complete the DB (Discussion Board) assignments for each module.
Sixth: Start thinking about your midterm project, final project, and final exam.
Seventh: Review the midterm exam and final exam study guides.
Eighth: Should you have any questions, comments, concerns, areas of improvement, and constructive criticisms;
please attend the weekly Office Hours/Live Sessions and/or contact me via the school's email system.
Ninth: If you are majoring in any IT (Information Technology) field
(especially for women and minorities),
you may want to check the Financial Aid section in any of my websites:
Scholarships or
Scholarships
For My Students and Visitors:
Comments, ideas, areas of improvement, questions, and constructive criticisms are welcome.
For All Those who Seek Peace:
Thank you for visiting.
Samuel Dominic Chukwuemeka (SamDom For Peace) B.Eng., A.A.T, M.Ed., M.S
(1.) Please review the
Rules of Netiquette
(2.) Please be creative.
Please paraphrase in your words as applicable.
(3.) No two posts should discuss the same thing.
Each post should be unique.
This implies that you should review any previous posts before you submit your own post.
(4.) The initial post is due on Thursday of the week for which it is required.
(5.) At least one response to the initial post is due on Saturday of the week for which it is required.
(6.) Only one thread per student is allowed.
Please do not create more than one thread.
Please respond to my comments (as applicable) in the same initial thread.
Please make any repost in the same initial thread.
Besides the Introduction DB (where I am required to welcome each student); usually, I make comments to some posts and some
responses submitted by Thursday of the week that a DB assignment is due.
If I make any comment to your initial post and/or response (submitted by Thursday); then it is very important you address any
concern in my comments.
If you do not understand my comments, please attend the Office Hours/Live Sessions and/or send an email to me and ask for
clarification.
I do not go back-and-forth (responding more than one time) to a student in DB forums.
The essence of DB forums is mainly for student communication and collaboration.
The professor only facilitates and makes few comments as necessary.
Typically, if I make any comment to your post and/or response for any DB assignment besides the Introduction DB,
it means that you need to fix some issues.
It is important you fix those issues to avoid deduction of points.
(7.) You may not do any of the same examples that I did for either a DB post or DB response.
(8.) You may do any of the questions in the Discuss tab as
a substantive post and/or substantive response.
(9.) You may make up your own substantive post and/or substantive response
if it is actually substantive.
However, in this case; it is very important you ask me for prior approval.
You may ask me during the Office Hours/Live Sessions and/or via the school's email.
(10.) You may solve the problems in the Assess tab as a DB assessment (post and response).
Questions in the Assess tab count for both DB post and DB response.
Each question in the Assess tab is to be uniquely done by only one student.
This means that it can be done by more than one student.
However, each post must be unique.
Further: For any Textbook Question:
(a.) Please submit a clear screenshot of the Question Number and the Question.
(b.) Any question from the textbook in the Assess tab should be done by only one student.
(11.) Sources must be cited accordingly.
You may use: APA (American Psychological Association) style, MLA (Modern Language Association) style, or the
Chicago Manual of Style.
(12.) Please submit clear screenshots.
For all applicable DB posts and responses, please use the Snipping Tool or the Snip & Sketch
on your computer to take clear screenshots
and trim off excess space/irrelevant information from your program code and output.
Then, use the Insert/Edit Image icon on the Blackboard editor to insert the screenshots of your code
and the output.
This is because your colleagues and I should be able to see your code and the output clearly.
Line numbers and all necessary details including the file names are also required.
You may need to increase the font size of your IDE so it is very clear.
You may need to take the screenshots of only the relevant window (the code window).
You may need to take several screenshots.
Also, please ensure you use a clear format for your writings.
Avoid any background colors in the Blackboard Editor.
(13.) Please do not submit an attachment for any DB assignment.
If you do, it will not be clicked. It will not be read. It will not be graded.
Your colleagues and I should be able to see your work directly without opening any attachment.
Any response to such post will not be counted.
Hence clear screenshots are required.
(14.) For all DB responses, please mention the first name of your colleague.
(15.) Provide a substantive response to your colleague.
A substantive response is the response that provides constructive criticism,
alternative approach that gives the same correct output, additional helpful information that will improve the post,
and the correction of any incorrect step and/or output among others.
How would you improve the initial post?
Did you find any errors in the initial post? If you do, please correct the error. Teach your colleague about the error, and
explain to him/her how to fix it. Provide screenshots as applicable.
What new knowledge can your colleague acquire from you based on your response?
Can you solve the initial post using an alternative approach that will give the same correct output?
What real-world examples/applications can you provide based on the initial post? Cite your sources accordingly.
Did your colleague learn anything meaningful from you based on your response to the initial post?
Please focus on the initial post. Do not deviate from the concept/topic in the initial post.
Do not bring up your own unrelated topic/concept.
Teach/Show your colleague something new and meaningful based on the initial post.
Write code examples as applicable, run them, and explain to your colleague.
Substantive responses should include screenshots as applicable.
(16.) Please use at least a size of 14 pt in your writings on the Blackboard Editor, and an acceptable
large font size on all your programs (IDE and output console among others).
(17.) Please proof-read your writings for mechanical accuracy errors.
Any use of "i" attracts deduction of points.
Multiple mechanical accuracy errors will lead to deduction of points.
I understand that this is not an English class. However, you are expected to write well.
(18.) Please make sure that you write comments for any program you submit.
Rule of Thumb for Comments (for academic purposes): Anyone (including those with little or no programming knowledge) should be
able to read your comments and have a basic idea of your program.
Unless written otherwise (for some questions), I am not saying you should write comments for every line of code.
I am asking you to write comments for every code block (section of code).
Do you read my comments? Of course, you should. I provide explanations in my comments.
Does it make sense? Yours should not be different.
Course using Java introducing concepts of software development, object-oriented event-driven programming, testing and debugging, simple and complex data types, language syntax and semantics. Prerequisite: None.
By the end of this course, you should be able to do the following:
(1.) Demonstrate best practices for designing end-user computing interfaces.
(2.) Discuss software development methodologies.
(3.) Use a programming or a scripting language to solve a problem.
(4.) Discuss significant trends and emerging technologies and their impact on our global society.
machine language, assembly language, low level language, high level language, IDE (Integrated Development Environment), text editor, compiler, development toolchain, linker, program,package, white space, braces, curly brackets, semicolon, variable, object, function, main function, integer, GUI, Graphical User Interface, Swing, Swing components, API, Application Programming Interface, NetBeans IDE, JFrame, application logic, program code, JavaFX, AWT, Abstract Window Toolkit, Event, Event Handler, Code,
Students will:
(1.) Download and install the NetBeans IDE or any suitable IDE for Java.
(2.) Discuss an overview of the Java programming langauge.
(3.) Write a simple program (Console Application) in Java
(4.) Write a simple program (Desktop Application) in Java
(1.) Textbook Chapter
(2.)
Lesson: Object-Oriented Programming Concepts: Practice the Questions and Exercises. Review the answers.
by Oracle
(https://docs.oracle.com/javase/tutorial/java/concepts/index.html)
(3.) Java Intro;
Java Syntax; and
Java Comments
by W3Schools
(https://www.w3schools.com/java/java_intro.asp)
(https://www.w3schools.com/java/java_syntax.asp)
(https://www.w3schools.com/java/java_comments.asp)
(4.) Designing a Swing GUI in NetBeans IDE
by Apache NetBeans
(https://netbeans.apache.org/kb/docs/java/quickstart-gui.html)
(5.) Learning Swing with the NetBeans IDE
by Apache NetBeans
(https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type Java in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type Java in the search bar and view/read the results.
00000 | 10011110 |
00001 | 11110100 |
00010 | 10011110 |
00011 | 11010100 |
00100 | 10111111 |
00101 | 00000000 |
Teacher: Please look at the code above.
Do you understand that code?
Student: The bunch of zeros and ones?
I have no idea what those mean.
int num1 = 3, num2 = 7;
System.out.println(num1 + num2);
Teacher: What about this code?
Do you understand it?
Student: I do not fully understand it.
However, it makes much sense than the first code?
Teacher: Both codes execute the same tasks.
Ask the user to input those numbers. Add those numbers. Output the sum.
Which code is better?
Student: The second code of course.
Teacher: The first code is the machine code.
It is the machine language.
It is a low level language.
It is the language the computer understands directly without translation.
The second code is the high level language.
It is the language humans can read and understand better.
Hence, there is the need to compile or interpret the high level language to
the machine language
so that computers would do what we want them to do.
There are four platforms of the Java programming language.
They are:
(1.) Java Platform, Standard Edition (Java SE)
(2.) Java Platform, Enterprise Edition (Java EE)
(3.) Java Platform, Micro Edition (Java ME)
(4.) Java FX
For this course, we shall only focus on writing Java programs using the Java Platform, Standard Edition (Java SE)
For information regarding these platforms: please review:
The Java Programming Language Platforms
(https://docs.oracle.com/cd/E19798-01/821-1770/gcrkk/index.html)
Java is one of the high level languages that we can use.
It is a compiled language.
This means that it is translated into machine language that can be understood directly by the
system.
In that regard, a set of tools are needed.
The set of tools is known as development toolchain
The core of the development toolchain are a compiler and its linker.
The best way to compile and run Java programs is to use an Integrated Development Environment
(IDE).
An IDE typically has several development tools including a text editor and tool to compile Java
programs directly.
For this course, the NetBeans IDE (it is free) is highly recommended.
However, you may choose to use any IDE that you wish.
What You Need:
(1.) Java Development Kit (jdk) of the Java Standard Edition (Java SE) Downloads
As at today: 08/27/2020; the latest Java SE is Java SE $14$:
Java Development Kit
(www.oracle.com/java/technologies/javase-downloads.html)
Click the JDK Download link.
For Windows users, select the Windows x64 Installer.
It has the executable file (the file that has .exe extension): jdk-14.0.2_windows-x64_bin.exe
Click the executable file, download and install it on your computer.
(2.) NetBeans IDE (Integrated Development Environment)
As at today: 08/27/2020; the latest version of NetBeans is the Apache NetBeans:
NetBeans IDE
Click the Download click on Download link.
If you do not know how to download and install any of these, please view the video.
Other ways to download, install, and run java programs:
(1.) Oracle
Tutorials
(2.) Java Get Started
If you are using the NetBeans IDE:
Please:
(1.) Review the screenshots of Module $1$ to increase the font size of your code in the IDE
(2.) Review the screenshots of Module $3$ to increase the font size of the output of your program in the IDE
Let us review each of these features.
If you do not get it now, no worries. You will get it later as you begin to work with it.
Let us begin with the Projects menu tab
So, we have created our first project named Module1
Note that it starts with an uppercase letter. The naming is either an uppercase or a Pascal case.
No worries, we shall discuss naming systems in the next module.
The java file in the project is Module1.java
It has the name of the project with the extension, .java
So, all java files has the .java file extension attached to the project name.
Analyzing Module1.java:
Lines $1 - 5$: Notice the words in those lines are blurred.
Those words are comments.
The comments are multi-line comments
So, you write a multi-line comment in Java by starting with a forward slash and an
asterisk and ending with an asterisk and a forward slash in that order.
Lines $8 - 11$ and Lines $14 - 16$ are also multi-line comments.
A multi-line comment is also known as a block comment.
Notice also that the words in Line $18$ is blurred.
However, Line $18$ is a single-line comment
You write a single-line comment in Java by writing two forward slashes before writing the
comments.
This is the same way we write single comments and multi-line comments in C++, C# and some other programming
languages.
Comments are required for any Java program you write in this course.
Rule of Thumb for writing comments (for academic purposes): Any person reading your comments should at a minimum, understand your
program and what your program is expected to do; regardless of the technology level proficiency of the person.
Please keep that in mind.
Please ensure you review the comments we write in our programs
Typically, every Java application program is inside a package.
A package is a namespace for organizing classes and interfaces.
Every code that runs in Java must be inside a method.
That method must be inside a class.
That class, typically should be inside a package.
We use the package to organize classes.
As we add more functionalities to our program, we may need to create more classes.
The package is used to organize all those classes.
In lay terms: The package of classes in Java is similar to the folder of several files in your
computer.
In programming terms: The package of classes in Java is similar to the namespace of classes in C#.
The name of the package is lowercase of the name of the Java file.
It could also something like com.samuelchukwuemeka (Notice it is the reversed order of the website
name: samuelchukwuemeka.com)
You should notice this naming for some IDEs. However, with the NetBeans IDE we are using; the package is
module1
As mentioned earlier, every code in Java must be in a method.
That method must be in a class.
This implies that every code in Java must run inside a class
A class is used for creating objects.
An object is an instance of a class.
This implies that whenever we call a class, an object is created.
It can also be defined as a software bundle of related state and behavior.
So, the Java programming language is an object-oriented programming language because it uses classes
to create objects.
If you do not understand these terms now, do not worry.
As we progress through the course and use them, it will begin to make sense...hopefully :-)
The name of the class must be the same as the name of the Java application or the file name
(without the extension).
This implies that the name of the class must be uppercase or Pascal case (as we mentioned earlier regarding the file
name).
In our case, it is Module1
Notice the public keyword before the Module1 class.
The public keyword is an access modifier
This means that that class can be used by other classes.
Student: Do we have private classes?
Teacher: Good question.
Our main class, the top-level class that has the same name as the file name must be public
However, we can have other classes inside that class (inner classes) that we can declare as private
Student: Are those the only two types of classes we can have?
Teacher: I guess the correct term would be: are those the only two access modifiers we have in Java?
We have another one: protected
We shall discuss these in details as we make progress.
So, we know that:
(1.) The name of the Java application must be uppercase or Pascal case.
(2.) The file name must be the name of the Java application with the .java extension.
So, the file name must be uppercase or Pascal case.
(3.) The package name must be lowercase or Camel case.
Typically, it is the lowecase form or the Camel case of the Java application.
(4.) The class name must be the same as the file name (without the extension, .java)
This implies that the class name must be uppercase or Pascal case.
Back to the comment in Line $18$: // TODO code application logic here
Any code we write inside that section will run.
That section begins from Line $17$ and ends on Line $19$.
It is known as the main method...Notice the bold italicized word in Line $17$, main
Any code inside the main() method will be executed.
So, we shall write our first code here.
We shall delete those default comments, write our own comments; and write our code.
To output our code/print the outout, we shall use the function
System.out.println("the output goes in here");
Our first code is THANK GOD
To print it, we write: System.out.println("THANK GOD");
Before we write our first code, I think it is better we change the font size of what se see now.
Let us make it bigger.
You can also change the comments, foreground color, and background color among others.
So, here are the steps to do that.
Let us go ahead and write code, and debug it.
If it passes debugging, then we run our it.
Example 1:
Student: It ran while you debugged it.
You did not click the Run menu.
Teacher: That is correct.
Student: So, does it matter if we run it right away?
Teacher: Yes, it does.
The essence of debugging is to check for errors.
If there are errors, you fix those errors before you run the program.
If there are no errors, then you run the program.
Student: So, what is the difference if we just run it?
Teacher: There will be no debug in the output.
Let's do it.
Example 2:
Example 3:
It will be nice to always put a new line or two new lines after our output.
This is done to separate the output.
We use the escape sequence, \n to insert a new line.
An escape sequence is a character preceded by a backslash (\)
It has a special meaning to the compiler.
Then, we click the green right arrow, the Run icon to run our program.
Example 4:
Example 5:
The font size of the output in NetBeans IDE is small.
Let us increase it.
Please see the steps/screenshots.
(1.) Create a desktop shortcut icon
(2.) Right-click
Open file location
You will see the shortcut icon on your desktop
(3.)
(4.) Add this code to the existing code: --fontsize 18
Before we continue, let us change the color of the comments
It is dull as it is.
I want my students to read the comments clearly
Tools → Options → Fonts & Colors → Category: Comment → I need it to be Dark Green.
Dark Green is not an option.
However, I can click Custom → RGB → and put a value of 0, 100, 0.
That is the RGB value for darkgreen color
Please see the images.
Let us reduce the font size of the output to 16.
I think size 16 is better. But you can leave it as 18.
Please see the images.
Student: What is the red vertical line in the code window?
It also appears in the screenshots.
It seems to be a problem with the NetBeans IDE.
Teacher: That vertical line is the Right Margin.
Let us remove it.
Tools → Options → Editor → Formatting → Uncheck All Languages Settings
→ Change the Right Margin to 0 → Apply → OK
Remove the vertical red line in the NetBeans IDE:
Example 6:
Let us review more code examples. Run the codes to see the output.
// Example 1: Write two different sentences on the same line
package module1
public class Module1{
public static void main(String[] args) {
System.out.println("Java is a programming language. It was developed by Oracle.\n\n");
}
}
// Example 2: Write two different sentences on two different lines using two System.out.println commands
package module1
public class Module1{
public static void main(String[] args) {
System.out.println("And now these three remain: faith, hope, and love. \n");
System.out.println("But the greatest of these is love.\n");
}
}
// Example 3: Write two different sentences using one System.out.println command
package module1
public class Module1{
public static void main(String[] args) {
System.out.println("And now these three remain: faith, hope, and love.\nBut the greatest of these is love.\n");
}
}
// Example 4: Write two different sentences using one System.out.println command
// But insert a blank line between the first line and the second line.
package module1
public class Module1{
public static void main(String[] args) {
System.out.println("And now these three remain: faith, hope, and love.\n\n"
+ "But the greatest of these is love.\n");
}
}
Please review the Teacher-Student scenario
Student: Mr. C, why do we need to develop desktop application?
Can't we just focus on console applications?
Teacher: Desktop applications are required for several DB assessments and for your Midterm Project.
It is optional for your Final Project.
It is important you learn to develop them.
Student: But, why?
Teacher: These are the reasons:
(1.) GUIs (desktop applications) cover a significant aspect of Number (1.) of the Student Learning Outcomes of the
course.
They also cover some aspects of Numbers (2.), (3.), and (4.)
(2.) You can run the executable JAR (.jar) file of a desktop application in any desktop/laptop that has
Java installed in it (both Windows and Mac)
Student: What are executable JAR files?
Teacher: Good question.
When you develop a Java program with Swing components such as the one we shall develop in a moment,
an executable file can also be developed. It is a file that is run on your computer to execute (do) something on your computer.
When you download and install a program on your computer (Windows users), it is normally seen as install.exe,
setup.exe or other "something".exe with the word, Application used to describe it.
In our case, it is going to be a standalone file with the jar extension described by
Executable Jar File that when downloaded in any desktop, can run when double-clicked.
Usually, you will get a warning from your computer not to download it because it can destroy your computer.
If you do not know the source/origin of the executable file, do not download it.
But in this case, we shall develop the program so we know it is safe.
When we develop the program, we need to follow these steps to locate the executable file.
Double-click: Application folder → dist → Application.jar
That Application.jar file is the executable file.
You can download it (no worries, it is safe), save it on your desktop, and run it on your desktop whenever
you want to.
Student: If I copy it to another desktop, will it run?
Teacher: Yes, it will run on any desktop provided that Java is installed on that computer.
That is the nice thing about it.
Student: Just that file?
It will run with all the functionality?
Without copying the entire folder?
Teacher: That is correct.
Click these links and review some of the desktop applications done by my students:
VB desktop applications and
C# desktop applications
These will run without any additional download.
Desktop applications are much better than console applications.
If you click the PROJECTS tab of this website and review the console applications done by my students,
you will realize that you need to type at least one command in the console before you can run the application.
If you review the PROJECTS (console applications) done by my C++ students,
it may require some program downloads to run on your machine (laptop/desktop).
You do not have to worry about typing commands or extra downloads when running desktop applications.
Student: Pretty cool.
Teacher: Yes, it is.
(3.) Assume you are working in a developing country (in Nigeria for example), you have a computer but no
internet service, and you really need to develop applications for the projects you are working on;
developing desktop applications is highly recommended in such cases because you do not need the Web/Internet
to run them. All you need is a laptop or desktop.
Student: But, I'm not working in Nigeria.
Neither do I intend to work there.
Teacher: What if you work for a multinational company and your compnay transfers you to work there?
What if you decide to join your church or organization on a charity mission trip?
(4.) Have you heard that the only thing that is not safe is anything on the Web?
Well-developed desktop applications minimizes your use of web and mobile applications, thereby minimizing cyber crimes.
There are limitations with desktop applications.
But, there are advantages too.
One of the advantages of Java is the developement of Desktop aplications.
Let me welcome you, my dearest students with a desktop application. 😊
As is the case for development of desktop applications, the three basic things to do are:
(1.) Create the user interface
(2.) Set the properties.
(3.) Write the program code.
The Swing API (Application Programming Interface) is used with the NetBeans IDE to develop Java desktop
applications.
JavaFX or AWT (Abstract Window Tookit) can also be used with NetBeans for GUI programming.
However, we shall be using the Swing API for this module.
JFrame Form
The form consists of:
(1.) Source Area (Source Window or Source View): This area contains the source code/program code/application
logic for the form.
(2.) Design Area (Design Window or Design View): This area contains the form.
I prefer Absolute Layout for the form because it implements a proportional positioning and sizing of the form
elements. Hence, I right-clicked on the form and selected Absolute Layout
However: please do not select any layout for your Midterm Project and Final Project
Student: Mr. C, you selected a layout for your application.
But, you asked us not to select any layout.
Hmmmm...why?
Teacher: I shall delete the layout later.
I just wanted to teach you about layouts.
Student: But why?
Teacher: Good question.
Layouts besides the Free Design layout require libraries.
When you publish an executable JAR file, the file will not work without the library.
I want a single executable file that anyone can click and run.
(3.) Palette: This area contains the tools/form elements.
It is similar to the Toolbox in the Microsoft Visual IDE. It consists of:
(I.) Swing Containers
(II.) Swing Controls
(III.) Swing Menus
(IV.) Swing Windows
(V.) Swing Fillers
(VI.) AWT: This is also used for GUI programming. It is Java's original GUI toolkit. We shall not use it for any of
our
tools. We shall be using Swing components/tools.
(VII.) Beans
If you point your mouse on any element/component/tool, a pop-up information regarding that tool is displayed.
(4.) Property Editor: This area contains the properties of each component.
We can change several porperties of each component such as the name property, title property, font property,
background
color property, and foregraound color property among others.
The Property Editor also contains Events (including Event Handlers) menu and Code menu.
(5.) Inspector: The Inspector provides a graphical representation of the components.
Let us review what we have discussed so far.
Please review the screenshots.
Create the User Interface and Set the Properties
(1.) Click the [JFrame] in the Inspector
Change the title in the Property Editor by clicking the ellipsis icon and typing Welcome to
our
Java Programming Class
(2.) Click on the form.
Let us change the background color.
I prefer Bisque background color.
The hexadecimal value of bisque is #FFE4C4
(a.) Right-click on the form and click Properties
(b.) Change the background property to the Color Code: #FFE4C4 under the RGB menu.
Teacher: It did not work.
The background color of the form has not changed.
Why is that?...speaking like an American lol
Student: Mr. C, you are asking me...seriously?
Teacher: Yes, I am asking you.
So, you can Bing it or Google it
Student: Okay Sir.
What should I type?
Teacher: Jframe form Swing NetBeans IDE background color not working
Look for any result from Stack Overflow
Student: What is Stack Overflow?
Teacher: It is Question-and-Answer forum for Computer Science.
The link is among the resources on the course website.
Student: Wow...pretty surprised you didn't answer me back with a set of questions.
Teacher: The questions I ask is meant to help you... to review all the resources I provide and to be a
problem solver and encouraging independent learning.
Programmers are problem solvers, you know.
Please do not take it in a bad way or rude way. The questions are meant to ensure that you understand all the
course
requirements and expectations.
Student: Whatever Mr. C
Teacher: What did you find? 😊
Student: There are several options I see here.
Teacher: Which option do you prefer?
Student: I think I prefer this one: adding a panel to the form and then changing the background color of
the
panel.
In this case, I think we should cover the entire form with the panel.
Teacher: Cool. Let's go for it.
Student: But, what is a panel?
Teacher: We'll see.
Just point your mouse to the Panel component to see what it is.
Then, click and drag it into the form and cover it.
(c.) Click the Panel component found in the Swing Containers and Drag it inside the form.
(d.) Adjust it to cover the entire form.
(e.) Right-click inside the panel and select Properties
(f.) Change the background property to the Color Code: #FFE4C4 under the RGB menu.
(3.) Adjust the size of the form and the panel as well.
This is necessary to accommodate our application.
I would like to introduce myself to my students and welcome them to our class.
But, I want it to be a surprise.
You like surprises?
(a.) When the form loads, there should be nothing in the form but only three buttons: Display, Clear
and Exit buttons.
When the user clicks the Display button, my Picture and the Welcome Message should be displayed
in the form.
When the user clicks the Clear button, my Picture and the Welcome Message should be removed
from the form.
When the user clicks the Exit button, the application should be closed.
(b.) So, I shall put my picture.
We do not have a Picture Box at the time of writing this application.
But, the Label in the Swing Controls can accept images.
So, we shall use the Label.
Adjust the size and display as you wish.
(c.) I have to write a Welcome to welcome them to our class, and also introduce myself.
The message will be written in multiple lines.
So, we shall use the Text Area
The Text Area is a multi-line area that displays plain text.
We shall change the font to Times New Roman and font size to $16$
Change the name to welcomeTextArea
(d.) We need the three buttons:
Change the name of the Display button to displayButton and the text to Display
Change the name of the Clear button to clearButton and the text to Clear
Change the name of the Exit button to exitButton and the text to Exit.
These buttons will perform some action when the user does an event such as the click event
For the three buttons: change the font to Times New Roman, the font size to $18$ and the background
color
to white
The hexadecimal value for white is FFFFFF
Select all three buttons using clicking on one and using the CTRL (Control key) to select the other two.
Set them to have the same width and height
Please review the steps in the screenshots.
Student: Mr. C, I hope you know the background colors of the three buttons did not change to white.
Teacher: No worries my dear. We changed it. You will see the change in the form when we run it.
Student: Is this not WYSIWYG? (What You See Is What You Get)?
Teacher: So, I clicked on each button (in the Design Area) and noticed that each of them has a white background.
When we run the program, we shall see the white background.
Program Code (Application Logic)
Now onto the functionality of the program.
This would be done in the Source Area
Please review the screenshots and the comments.
Remember we unchecked the Main Class when we created this project.
This is because our GUI program will be the Main Class.
We shall now select it as the Main Class.
Source Code
This includes my code and the auto generated code.
Do not worry about the auto generated code.
Focus on my codes and my comments.
My comments explained the codes.
Run the program
Click events by the User
Publish our GUI as a Desktop Application
This means that we have to create an executable JAR (Java ARchive) file.
To do this, we need to Clean and Build Project (Clean and Build the Introduction project) or press the
Shift + F11 keys on
your keyboard.
When this is done, the dist folder is created.
That dist folder contains the Executable JAR file.
Please review the screenshots.
This is the Introduction.jar executable file
You may click the link to download and run it. No worries, it is safe.
It is a desktop application.
If you have Java on your computer (PC or Mac desktop/laptop), click the file and run the application directly on your desktop.
Student: I have a question.
If I decide to make some changes to the code, will those changes be automatically reflected in the app
even though the app has been published?
Teacher: Good question.
Whenever you make changes to your program code, then you will need to Clean and Build Project again.
An updated executable jar file will then replace the previous one.
So, you will need to re-download the new file.
When you run the file, did you notice my picture is not diplayed even when you click the Display
button?
This is one of the reasons why I ask you not to include pictures in your desktop applications for the
Midterm Project and the Final Project.
Please do not include any picture in your Midterm Project and Final Project applications.
(1.) Discuss a brief history of Java.
(2.) Discuss the versions of Java including any significant change made for each version.
(3.) Discuss any console application developed with Java.
(4.) Discuss any desktop application developed with Java.
(5.) Discuss any web application developed with Java.
(6.) Discuss any mobile application developed with Java.
(7.) Discuss any IDE for Java including the advantages and disadvantages.
(8.) Explain using appropriate examples, any three new terms learned in this module.
(9.) Compare any three features of Java with any similar object-oriented language.
(10.) Contrast any three features of Java with any similar object-oriented language.
(11.) Write two different sentences on two different lines.
Insert a blank line between the first line and the second line.
Do NOT use the escape sequence.
(1.) Include any missing gaps in the history of Java.
(2.) Include any missing gaps in the versions of Java.
(3.) Discuss an additional console application developed with Java.
(4.) Discuss an additional desktop application developed with Java.
(5.) Discuss an additional web application developed with Java.
(6.) Discuss any mobile application developed with Java.
(7.) Discuss any IDE for Java. Include the advantages and disadvantages.
(8.) Add to the post of the student who explained any three new terms learned in this module.
(9.) Add to the post of the student who compared three features of Java with another
object-oriented langauge.
(10.) Add to the post of the student who contrasted three features of Java with another
object-oriented langauge.
(11.) Provide any of these if it is lacking in any DB post that solved any question in the
Assess tab of this module: Well-written comments; another approach/method to solving the
question; any additional relevant details; etc.
(12.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(1.) Develop a desktop application titled: Introduction
The application should include three buttons: the About button, the Clear button, and the
Exit button.
When a user opens the application, it should display a blank page and the three buttons.
When the user clicks the About button, these information should be displayed:
(a.) Your picture
(b.) A brief summary of you. Write at least three sentences about yourself.
(c.) One sentence about the course and your major/program.
(d.) One sentence about the course expectations/accomplishments. What is your expectation about the course? What
do you intend to accomplish at the end of the course?
(e.) Any other thing you would like us to know about you.
When a user clicks the Clear button, the page should be blank.
When a user clicks the Exit button, the application should close.
I am more interested in the functionality.
However, I am also interested in the design/graphics/aesthetics.
Make a good design.
(2.) Write two different sentences on two different lines.
Insert a blank line between the first line and the second line.
Do NOT use the new line command (new line escape sequence).
vary, variable, identifier, data type, data value, value, container, ASCII (American Standard Code for Information Exchange), character (char), primitive data type, non-primitive data type, object, method, class, dot access operator, new line, size, storage, precision, type casting, widening casting, narrowing casting
Students will:
(1.) Discuss the meaning of variables in Java
(2.) Discuss the data types in Java
(3.) Discuss the rules for using identifiers.
(4.) Write Java programs that involves the use of variables and data types.
(1.) Textbook Chapter
(2.) Java Variables, Java Data Types, and Java Type Casting by W3Schools
(https://www.w3schools.com/java/java_variables.asp)
(3.) Operators by Oracle
(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html)
(4.) Conversions and Contexts by Oracle
(https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html)
(5.) Designing a Swing GUI in NetBeans IDE
by Apache NetBeans
(https://netbeans.apache.org/kb/docs/java/quickstart-gui.html)
(6.) Learning Swing with the NetBeans IDE
by Apache NetBeans
(https://docs.oracle.com/javase/tutorial/uiswing/learn/index.html)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(7.) Type Java Variables and/or Java Data Types in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(8.) Type Java Variables and/or Java Data Types in the search bar and view/read the results.
A Variable is a portion of computer memory for storing a data value.
Because a variable stores a data value, it is important to identify the type of data value it
stores.
This implies that any variable is associated with a data type.
The data type describes the type of data value stored by the variable.
What type of data is being stored? Are they numeric (numbers), non-numeric
(letters/characters/words), etc.?
As noted with the word: variable, any value stored by it can vary (can
change).
A variable is created/declared in Java by specifying the data type associated with it and assigning it to a value.
We declare a variable this way:
datatype variable = value
The equal sign is the assignment statement.
In other words, you assign something in Java using the equal sign.
Let us review the data types in Java.
Data types in Java are:
(1.) Primitive data types
(2.) Non-primitive data types.
A primitive data type is the data type that specifies the size and type of the values
of the variable.
It is predefined in the Java language. This means that it is already defined in the Java language.
It always has a value. It cannot be null.
When a primitive data type is declared, it always begins with a lowercase letter.
Primitive data types have various sizes depending on the data type. The sizes are not the same.
It cannot be used to call methods.
As of today: 09/03/2020; there are eight primitive data types in Java.
They are:
Primitive Data Type | Declaration | Size | Description |
---|---|---|---|
(1.) Integer (Byte) | byte | 1 byte (8 bits) | Integers from -128 to 127 are stored |
(2.) Integer (Short) | short | 2 bytes (16 bits) | Integers from -32,768 to 32,767 are stored |
(3.) Integer (Integer) | int | 4 bytes (32 bits) | Integers from -2,147,483,648 to 2,147,483,647 are stored |
(4.) Integer (Long) | long | 8 bytes (64 bits) |
Integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 are stored NOTE: End any integer declared with the long data type with an uppercase L |
(5.) Floating Point (Float) | float | 4 bytes |
Up to 7 decimal places are stored. NOTE: End any decimal declared with the float data type with a lowercase f |
(6.) Floating Point (Double) | double | 8 bytes |
Up to 15 decimal places are stored. NOTE: End any decimal declared with the double data type with a lowercase d |
(7.) Boolean | boolean |
1 bit 0 = false, 1 = true Make the connection with electronic devices. 0 = Off; 1 = On |
Only false and true values are stored Displays as 0 and 1 respectively |
(8.) Character | char | 2 bytes |
Only a single character/letter is stored. The decimal values of ASCII characters/values are also stored. NOTE: If you intend to use the decimal values of ASCII characters/values, you must declare it with the char data type and the decimal value should not be included in quotation marks. |
Student: You have talked about size. But, you said it cannot call methods.
May you please explain?
Teacher: We shall discus it later.
Let us look at non-primitive data types.
Student: That is the issue.
I get lost when you keep going.
Is it not better to explain any concept you mention? Also give examples.
Teacher: No worries.
Let us look at the non-primitive data types.
The non-primitive data types can call methods/functions.
Then, we discuss variables.
Then, we can review some examples.
Student: Now, you mention functions
Teacher: A method is a function
There are some concepts we shall mention, but not discuss immediately.
We shall discuss those concepts in later modules.
Some of those concepts would be discussed in the next course.
A non-primitive data type is the data type that refers to objects.
Because it refers to objects, it is also known as a reference type.
When a non-primitive data type is declared, it always begins with an uppercase letter.
Non-primitive data types have the same size.
They are used to call methods.
Besides the String data type, all other non-primitive data types are not predefined in the Java language.
They are defined by the programmer. This implies that the String data type is the
only non-primitive data type that is predefined in the Java language.
Non-primitive data types may or may not have a value. They can be null.
Examples of non-primitive data types are: Strings, Arrays, Classes, and Interface
among others.
Let us review the variables in Java.
Java variables are identified with unique names known as idenfiers.
It is important to use identifiers that are meaningful and descriptive.
Anyone reviewing your program should not have to guess the meaning of your variable.
As you can see (based on the image below: Variables, Data Types, Values:)
The variables I used in that example are meaningful and descriptive
Those variables are:
state to denote the State of Ohio, OH
numState to denote the number of the State of Ohio in an alphabetical listing of the
state names
povertyRate to denote the poverty rate of Ohions according to the $2000$ census data
landArea to denote the land area of the Ohio according to the $2000$ census data
motto to denote the motto and seal of the Great State of Ohio
ismottoTrue to denote the Boolean data type if the motto is true
Even without the comments, you already have an idea of the meaning of my variables.
I should not have to guess the meaning of your variables.
Variable names:
(1.) Can be single letters (please avoid unless if used in loops)
(2.) Can contain a combination of letters, digits, and underscores but must not begin
with a number.
It may begin with a letter or an underscore.
(a.) Please avoid underscores
Avoid underscores even if the variable name does not begin with an underscore.
(b.) Use a combination of letters and digits such as:
num1 to represent the first number
variable1 to represent the first number
(3.) Can contain only letters but must not be any of the reserved keywords.
The reserved keywords that are still in use are:
abstract, assert, boolean, break, byte, case, catch, char, class, continue, default, do, double, else, enum,
extends, final, finally, float, for, if, implements, import, int, interface, long, native, new, package, private,
protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient,
try, void, volatile, while
The reserved keywords that are not in use are:
const, goto
The const keyword is replaced with the final keyword.
NOTE: You cannot use any of the reserved keywords as an identifier/variable name regardless of whether
they are in use or not in use.
(a.) The letters can be Camel case (similar to the hump of a camel) such as:
firstVariable...the V is the hump
In Camel casing letters: two letters are merged as one; the first letter of the second word is
an uppercase letter while all other letters are lower case letters.
In firstVariable, V is uppercase; all other letters are lower case
(b.) The letters can be Pascal case such as FirstVariable
In Pascal casing, two letters are merged as one; the first letter of the first word and the
first letter of the
second word are uppercase letters while all other letters are lower case letters.
In FirstVariable, F and V are uppercase; all other letters are lowercase.
(c.) uppercase letters (please avoid...it denotes someone who is yelling)
(d.) lowercase letters (okay, but try to avoid)
Student: What if you have three words?
How do you write it in Camel case? Pascal case?
Teacher: Say we want to write the variable, first arithmetic sequence
Camel case: firstArithmeticSequence...A and S are the only uppercase
Pascal case: FirstArithmeticSequence...F, A, S are the only uppercase
In this course, for all applicable variables; please use:
(i.) A combination of letters and digits such as num1 OR
(ii.) Camel case letters such as firstNumber OR
(iii.) Pascal case letters such as FirstNumber
***We shall use single characters when we write conditions for Iteration statements/Loops
because it is
easier to use single characters in such cases. We shall see examples when we discuss loops.
However, feel free not to use it if you wish.***
(4.) Can contain only letters but must not be these literals: true, false, null
(5.) Cannot contain whitespaces or special characters.
The special characters are all the non-numeric and non-alphabet characters on your keyboard such
as ~ (tilde), !(exclamation), @ (asperand), # (hash), $ (dollar), % (percent), ^ (caret), & (ampersand), *
(asterisk).
A whitespace is a horizontal or vertical space.
For example: myNum has no whitespace; but my Num has a whitespace.
Variable names cannot contain whitespaces.
Hence: myNum is acceptable, but my Num is not acceptable.
Declaring Read-Only Variables: Use the final keyword (constant keyword)
As we have learned, a variable vary. The value changes.
However, read-only variables do not change.
Sometimes, we need these kind of variables.
We have to create/declare them using the final keyword.
For example, if we want to use the approximate value of pi as $3.142$ rather than using the
exact value, we can declare it as:
final int $piValue = 3.142$
This means that the variable, piValue is a read-only variable
It will not change it's value.
Student: May you please give code examples?
Teacher: Sure.
Let us review these two examples.
We shall create a new project, Module 2
So, we have two projects: Module 1 and Module 2
Before you run Module2.java, you will need to:
(1.) Close Module1.java from the code window.
(2.) Open only Module2.java in the code window.
(3.) Click the Run menu tab. Then, click Clean and Build Project (Module 2)
Do these steps whenever you create and want to run a new project without deleting any previous projects.
As you can see, the variable piValue2 cannot be changed because it was declared as a read-only
variable (using the final keyword)
Teacher: As you see: for the new value of piValue1, we can modify the value of any variable we create, by specifying another value for that same variable name.
Student: But, why do we need to do this?
Can't we just create another variable with that second value?
Teacher: Good point.
Yes, it is much better to create another variable with the new value.
However, when we work with statements and sorting techniques among others; it may be more efficient to just assign the new value to the same variable; rather than create another variable and assign the new value to it.
For example: if you are sorting through a loop also known as an iteration statement; we can create a variable, and write a conditional statement that when you compare an element in the array with the next element; assign the value of the greater element to the variable.
Rather than create a new variable, assign any greater value to the variable as you compare elements in the array.
There are some terms I just used, that we shall discuss in later modules.
(6.) Are case sensitive.
These are all different variables:
firstresult (lowercase), firstResult (Camel case), FirstResult (Pascal case), Firstresult,
FIRSTRESULT (uppercase),
first_result (snake case)
Let us review more variable examples in Java
A variable can store the number, say 5 in a line of code; and the same variable can store a different number, say 7
in another line of code.
So, the values stored by a variable can change.
An example with integers:
An example with strings:
Teacher: Back to your question regarding a method
Did you notice we used the println() method and the lineSeparator() method?
We used the System class to call those methods using the dot access operator.
The period punctuation mark is known as the dot access operator.
Student: So, the method belongs to that class?
Teacher: That is correct.
Hence we were able to call it.
Student: So, what is a class? Also, you mentioned object initially?
Teacher: We create a class in Java.
When we want to use that class, we have to call it.
Calling that class means creating an object.
We shall discuss these terms later.
Student: So, what you are saying is that primitive data types cannot call a method, but non-primitive data types can?
Teacher: That is correct.
Student: May you show me an example?
Teacher: Please wait. When we discuss Strings, we shall review examples.
Variables, Data Types, Values:
Type Casting is the conversion of a value from one primitive data type to another
primitive data type.
Type casting in Java can be:
(1.) Widening Casting is the conversion of a value from a smaller primitive data type to a
larger primitive data type.
byte to short byte to char byte to int byte to long byte to float byte to double short to char short to int short to long short to float short to double char to int char to long char to float char to double int to long int to float int to double long to float long to double float to doubleThis is done automatically.
double to float double to long double to int double to char double to short double to byte float to long float to int float to char float to short float to byte long to int long to char long to short long to byte int to char int to short int to byte char to short char to byte short to byteThis is done manually.
As usual, we shall develop desktop applications that involves the use of variables and data types.
Let us develop desktop applications for the console application we did for the State of Ohio
We shall use several toolboxes (Palette tools).
Remember that the Midterm Project is a desktop application.
Hence, it is necessary to start getting familiar with GUI programming.
Please review the desktop application we did in Module $1$ to understand the basic steps.
We shall give appropriate names for our projects.
JFrame Form: Adjust and Align
title property: State of Ohio: Labels and Buttons
Palette | Property |
---|---|
Panel Adjust and Align to cover entire JFrame Form |
background: RGB → Color Code: F5DEB3 (This is for the color: Wheat) font: Font: Times New Roman; Font Style: Plain; Size: 24 Change Variable Name: ohioPanel |
Label 1 (LHS): Adjust and Align |
text: State font: Font: Times New Roman; Font Style: Plain; Size: 24 |
Label 2 (RHS): Adjust and Align |
border: Etched Border Please see image below the table for illustration (Setting the border should be done first) Adjust and Align again font: Font: Times New Roman; Font Style: Plain; Size: 24 Change Variable Name: stateLabel |
Right-click the State label and Duplicate Please see image below the table for illustration |
text: Number |
Right-click the Label 2 and Duplicate Please see image below the table for illustration |
Change Variable Name: numberLabel Adjust and Align the Number text label to be in line with the numberLabel name label |
Select both the Number text label and numberLabel name label by: Clicking on them, holding
the CTRL key on your keyboard, and clicking on the other one. How do you know if it was done well? The Properties Area indicates Multiple Objects. Right-click Duplicate Both labels are duplicated. Please see image below the table for illustration Click on each label and make changes as noted below. Adjust size and Align as necessary. Do this for the rest of the labels. |
|
Duplicate Label |
text: Poverty Rate Change Variable Name: povertyRateLabel |
Duplicate Label |
text: Land Area Change Variable Name: landAreaLabel |
Duplicate Label |
text: Motto Change Variable Name: mottoLabel |
Duplicate Label |
text: Is Motto true? Change Variable Name: booleanLabel |
Button |
text: State of Ohio font: Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB → Color Code: FFFFFF (This is for the color: White) Change Variable Name: ohioButton |
Duplicate Button |
text: Clear Change Variable Name: clearButton |
Duplicate Button |
text: Exit Change Variable Name: exitButton |
Set the border of the RHS Labels
Duplicate Labels
Duplicate both Labels at the Same Time
We discussed the other tasks in Module 1.
(1.) Run the program and select OhioFlashcard1 as the main class.
Close the application and let us code the program.
(2.) In the Design Area, double-click the State of Ohio button.
This leads to the Source Area
Scroll all the way to the top and begin to ...
(3.) Write the code.
Please review the screenshots.
Review the comments.
Design Area
Program Code
Run the Program
In the previous application, I closed the Palette (Toolbox) Area and the Properties Area so I can have
more space for the interface.
I used a laptop and I needed more space in the Design Area
To view the Palette and the Properties Area, please click: $Window \rightarrow IDE\;\;Tools \rightarrow Palette$ and
$Window \rightarrow IDE\;\;Tools \rightarrow Properties$
It is also shown in the screenshots below.
Please review the previous GUI applications.
JFrame Form: Adjust and Align
title property: State of Ohio: Text Area and Buttons
Palette | Property |
---|---|
Panel Adjust and Align to cover entire JFrame Form |
background: RGB → Color Code: FFF8DC (This is for the color: Cornsilk) font: Font: Times New Roman; Font Style: Plain; Size: 24 Change Variable Name: ohioPanel |
Text Area: Adjust and Align |
font: Font: Times New Roman; Font Style: Plain; Size: 24 Change Variable Name: ohioTextArea |
Button: Adjust and Align |
text: State of Ohio font: Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB → Color Code: FFFFFF (This is for the color: White) Change Variable Name: ohioButton |
Duplicate Button: Adjust and Align |
text: Clear Change Variable Name: clearButton |
Duplicate Button: Adjust and Align |
text: Exit Change Variable Name: exitButton |
(1.) Run the code and select OhioFlashcard2 as the main class.
Close the application and let us code the program.
(2.) In the Design Area, double-click the State of Ohio button.
This leads to the Source Area
Scroll all the way to the top and begin to...
(3.) Write the code.
Please review the screenshots.
Review the comments.
Design Area
Program Code
Run the Program
We shall explore more Palette tools (toolbox controls) in subsequent modules.
(1.) Using at least five complete sentences and at least five different variables and data types,
write a program of the summary of what you learned in this module.
(2.) Write a program of a short story, a poem, or drama using at least five sentences and at least five different variables and data types.
(3.) Write a program that displays examples of all the Primitive data types and the String data type.
(4.) Write a program that demonstrates at least ten examples of Widening Type Conversions
Use the data types listed in this Module.
(5.) Write a program that demonstrates at least ten examples of Narrowing Type Conversions
Use the data types listed in this Module.
(6.) Write a program of a short story, a poem, or drama using at least five sentences, the same variable,
and at least three different data types.
For Question (7.)
Please review: Conversions and Contexts
(https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html) for the other conversions.
Specific type conversions in the Java programming language are divided into 13 categories.
(I.) Identity Conversion
(II.) Widening Primitive Conversion
(III.) Narrowing Primitive Conversion
(IV.) Widening and Narrowing Primitive Conversion
(V.) Widening Reference Conversion
(VI.) Narrowing Reference Conversion
(VII.) Boxing Conversion
(VIII.) Unboxing Conversion
(IX.) Unchecked Conversion
(X.) Capture Conversion
(XI.) String Conversion
(XII.) Forbidden Conversions
(XIII.) Value set Conversion
(7.) Using at least five complete sentences and at least five different variables and data types,
discuss any of the conversions that we did not discuss in this module.
(8.) We have discussed several ways of displaying the output in a new line.
Please review all the comments in the screenshots.
Do you know of any other way/ways we can display the output in a new line besides what we discussed?
What are those ways?
Write them. Run your code and display the output.
(9.) We have discussed at least two ways of printing a decimal with a % (as seen in the povertyRate variable).
Please review all the comments in the screenshots.
Do you know of any other way/ways we can print a decimal with the percent sign besides what we discussed?
What are those ways?
Write them. Run your code and display the output.
Textbook Questions
(10.) Question $4$ on Page $106$
(11.) Question $6$ on Page $106$
(12.) Question $8$ on Page $106$
(13.) Question $10$ on Page $107$
(1.) Provide any of these details if they are lacking in any DB post:
Well-written comments; another approach/method to solving the question; any additional relevant details; etc.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
(1.) Develop a Graphical User Interface (GUI) of a short story, a poem, or drama using at least five sentences and
at least five different variables and data types.
At least three buttons: the button that displays the information, the Clear button and the
Exit button should be included.
(2.) Develop a Graphical User Interface of a short story, a poem, or drama using at least five sentences,
the same variable, and at least three different data types.
At least three buttons: the button that displays the information, the Clear button and the
Exit button should be included.
(3.) Develop a GUI flashcard of all the Primitive data types and the String data type.
A brief definition of each data type should be displayed when the user performs an event
(such as pointing the mouse or clicking) on each data type.
Use whatever palette (toolbox controls) you prefer.
operator, operation, operand, operator precedence, assignment operator, arithmetic operators, addition operator, subtraction operator, division operator, remainder operator, modulo operator, compound assignment operators, unary operators, unary plus operator, unary minus operator, increment operator, decrement operator, increase, decrease, logical complement, logical operators, bitwise and bit shift operators, conditional ternary operator (ternary operator), equality and relational operators, comparison operators, conditional operators, format specifier, input-output feature,
Students will:
(1.) Discuss the operators in Java
(2.) Perform operations on variables/values
(3.) Write Java programs involving the use of operators.
(1.) Textbook Chapter
(2.)
(A.) Operators by Oracle
(B.) Summary of Operators by Orcale
(C.) Questions, Exercises, and Answers by Oracle
(3.) Java Operators and
Java Math by W3Schools
(4.) (A.) Java User Input by W3Schools
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(5.) Type Java Numbers and/or Java Operators in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(6.) Type Java Numbers and/or Java Operators in the search bar and view/read the results.
Operators are special symbols that perform specific operations on one or more operands,
and returns an output.
An Operand is the variable/value on which an operation is done.
Operators | Symbols | Description | Code Examples |
---|---|---|---|
Assignment | $=$ | Equal sign |
int num1 = 7;
|
Arithmetic Addition Subtraction Multiplication Division Remainder (Modulo) |
$+$ $-$ $*$ $/$ $\%$ |
Add Subtract Multiply Divide Remainder after a division |
int num1 = 6, num2 = 2;
|
Compound Assignment Plus equal Subtract equal Multiply equal Divide equal Modulo equal |
$+=$ $-=$ $*=$ $/=$ $\%=$ |
Add, then equal to Subtract, then equal to Multiply, then equal to Divide, then equal to Remainder after division, then equal to |
int num1 = 5;
|
Unary Unary plus Unary minus Increment Decrement Logical complement |
$+$ $-$ $++$ $--$ $!$ |
The unary operators require only one operand. Unary plus operator example $+=1$ means Increase by one Unary minus operator example $-=2$ means Decrease by two The increment, ++ and decrement, -- operators can be: prefix or postfix (suffix) Prefix Increment (evaluate the value, after it is increased) Postfix (Suffix) Increment (evaluate the value, before it is increased) Prefix Decrement (evaluate the value, after it is decreased) Suffix Decrement (evaluate the value, before it is decreased) Logical complement operator inverts(negates) the value of a boolean |
int num1 = 9;
|
Conditional Ternary |
$?$ |
The Conditional ternary operator evaluates an expression amidst two results. If the expression is true, it returns the first result. If the expression is false, it returns the second result. The two results are separated by a colon : The expression is separated by the two results using the conditional tenary operator (question mark) ? The syntax is:
expression ? result1 : result2
|
int num1 = 5, num2 = 2;
|
Equality and Relational Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to |
$==$ $!=$ $\gt$ $\lt$ $\ge$ $\le$ |
Equality and Relational Operators are used to compare two expressions. The result is a Boolean (either true or false) |
int num1 = 5, num2 = 2;
|
Please review the rest of the Operators
Let us review more examples of Arithmetic Operators and Math Functions.
A Simple Arithmetic Operation of Two Integers:
Teacher: Did you notice the quotient?
Student: Yes, Sir. I did.
That result is incorrect.
Teacher: Yes, it is.
Any suggestions?
Student: I think it is because it was declared as an integer.
Teacher: Correct.
How do we fix it?
Student: Declare it as a float?
Teacher: Let's see
Teacher: We ran into another problem.
Student: What problem?
Are those answers not correct?
Teacher: They are correct.
However, the sum, difference, and product are not really floats.
They are integers.
Student: Does it really matter?
$12.0$ is the same thing as $12$
Teacher: But, we want to display it as an integer.
What should we do?
Student I have no idea.
Teacher: We discussed it in last module.
Student Wait...let me check
Type casting?
Teacher: What type?
Student: Narrowing Casting
Teacher: Because?
Student: We want to convert from a larger type (float) to a smaller type (integer)
Teacher: That is correct.
Let's do it.
Student: That fixed it.
Teacher: It did.
But, not really.
Student: What do you mean by "not really", Sir?
Teacher: The floating type.
The precision of the floating data type...
is less than that of the double data type
Teacher: What if I do not want you to round?
Or what if I want more precision?
What should we do?
Student: Use the double data type?
Teacher: That is correct.
Let's do it.
Teacher: Is that not better?...in terms of
better precision...greater number of decimal places?
Student: But, would you require our answers like this?
How do we know what format the output will be?
Student: Would you take off points for something as minor as $12.0$ rather than $12$?
Teacher: Here is my advice.
If you know the answer of the output, then declare the input variables with the appropriate data type.
For example: we know the sum is $12$.
So, if we were to find only the sum, we would just declare both num1 and num2 as integers because the output
will
give us an integer.
However, if we do not know the format of the output:
Begin with the double data type because it has more precision.
If your output turns out to be an integer, narrow cast that double data type to an integer
If the output is an integer, but your output is a float or double; I shall deduct points.
One of the nice things about the NetBeans IDE is that it will help you with the type casting.
If you see a red line and you point your mouse at it, it will ask you to press the Alt and Enter
key
to show hints. When you do that, one of the hints will be to type cast/do the conversion. Click it and
the IDE will do it for you.
We have reasons for rounding numbers. We also have reasons for not rounding numbers.
Let us solve more questions.
NOTE:
Jave recommends that we should never use the float or double data type for precise values, such as
currency. (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)
It recommends that we use the java.math.BigDecimal class instead.
When we begin our study of classes (in the next course), we can review that class and other APIs (Application
Programming Interface).
For this course, we shall use the double data type.
Let us review more examples.
Please visit my website on Numbers
(www.numbersandnotations.appspot.com/numbers.html)
Let us solve Question $10$ on that website
First Approach
We used the Java Math Functions in this approach.
Please see the complete list of the Java Math Functions
(https://docs.oracle.com/cd/E17904_01/apirefs.1111/e12048/functmath.htm#CQLLR412)
Second Approach
Let us review a case where the answer needs to be rounded.
Please visit my website on Percent Applications
(www.fractions-decimals-percents.appspot.com/percentApplications.html)
Let us solve Question $1$ on that website
We can round any value to any number of decimal places in Java.
Let us discuss at least two ways we can do it.
Both approaches involves String variables.
(1.) Importing the Java class: import java.text.DecimalFormat;
I listed this approach first because it is popular with programmers.
I prefer the third approach, but you can use whatever you prefer.
(2.) Using the String.format() method.
(3.) Using the Print Formatted method System.out.printf() method.
This is my preference.
To see the examples where I used this approach, please view the screenshots of Piecewise Functions in
Module $5$.
For example:
System.out.printf("$%.2f\n", costOrder);
$ puts the dollar sign
%.2f rounds the value to two floats (two decimal places)
\n inserts a new line
Please review the screenshots and the comments for explanations.
We can solve the same question using only one variable.
In this case, we have to use Compound Assignment Operators
Question $1$ on Percent Applications
Using Compound Assignment Operators:
Please review the screenshots and the comments for explanations.
Student: Mr. C, I do not want to be confused by what you do.
Teacher: What is it my dear?
Student: You did not put d in the previous examples.
Then, you put d in this example.
That is confusing...you do something for one and you do another thing for another.
Teacher: I understand.
It is recommended that you put d when you declare a double data type for a variable
However, by default; any decimal in Java is seen as a double data type.
That is also another reason to use the double data type rather than the float data type.
The first reason is because of the precision.
Another reason is that any decimal number in Java is a double data type by default.
So, if we forget to include the d after the decimal, that is not a problem.
It is better to include it.
But, it is not a problem if you forget to include it.
Student: Okay.
What if I write: final float salesTax = 0.12
Will it work?
Teacher: No, it will not work because the decimal number is a double data type in Java by default.
If you want to use a float for that, you will need to include the f after the decimal number
Like final float salesTax = 0.12f will work as a float.
However, keep in mind that the rest of the variables will have to be floats as well. Otherwise you will have to convert them to floats.
It is much better to use the double data type.
Nice observation!
In the formatted methods (String.format() and prinf()) that we used: the format specifiers:
For example in:
System.out.printf("$%.2f\n", costOrder);
$ puts the dollar sign
%.2f rounds the value to two floats (two decimal places)
\n inserts a new line
One of the nice features of the Java langauge is the Input/Output feature.
This feature is interactive.
You use this input/output feature in several applications.
A common application is an application that verifies one's identity by inputting the first name, last name, date of
birth, etc.
To use the Input/Output feature, the Scanner is used.
In other words: write import java.util.Scanner; directly under the package.
This means that you want to: Import the Scanner class of the java.util package
Let us demonstrate the input/output feature with numbers so we see how it works.
Please review the screenshots and the comments.
Java Input/Output Feature for Arithmetic Operations and Math Functions.
Let us do another example.
Input/Output Feature: Example $2$
Let us do a real-world application for this example.
Onto the ...
Please review the BMI information on these two government websites [from the Center for Disease Control and Prevention (CDC) and the National Heart, Lung, and Blood Institute of the National Institutes of Health (NIH)]
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC and
Calculate Your BMI - Standard BMI Calculator
As at today, the 3rd day of September, 2020; the BMI information on both websites are:
NIH website
Calculate Your BMI - Standard BMI Calculator
CDC website
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC
$ BMI = \left(\dfrac{weight}{height * height}\right) * 703 \\[5ex] weight\:\:is\:\:in\:\:pounds (lb) \\[3ex] height\:\:is\:\:in\:\:inches (in) $
$ BMI = \left(\dfrac{weight}{height * height}\right) \\[5ex] weight\:\:is\:\:in\:\:kilograms (kg) \\[3ex] height\:\:is\:\:in\:\:meters (m) \\[3ex] $ If you need help with conversion of units, please review the Tables and Examples in Measurements and Units
Teacher: What do you notice in both websites?
Student: They both have the information on the BMI.
In addition, the CDC website has information for both Adult BMI and Child & Teen BMI among others.
The NIH website has recommendations among others.
Teacher: That is correct. What else?
Student: They have the BMI calculator.
Teacher: Did you notice any difference in the calculator on both websites?
Student: The NIH website has BMI calculator for both Standard and Metric versions.
The CDC website has the BMI calculator for only the Metric version.
Teacher: Did you notice any issue/concern about the BMI information?
Student: Not really. Why?
Teacher: So, this is what we are going to do.
Let us develop the BMI calculator.
That calculator will calculate the BMI.
Then, we shall interpret that BMI, and make a recommendation.
.
The CDC website gave us the formula for calculating the BMI. So, we shall use it.
As you can see, our calculator would have to use conditional statements for the interpretation and recommendation.
But, here is the issue.
Student: Wait, I think I see the issue.
The issue is with the domains.
Teacher: Correct!
Anyone having a BMI between $18.5$ and $24.9$ both endpoints included has a Normal weight.
This is: Normal weight: [18.5, 24.9]. It is a closed interval (relate with Mathematics).
So, the Overweight range for the BMI should be the weight greater than $24.9$, (rather than beginning from $25$) and ending at $29.9$
For the Overweight range, the first endpoint is not included, but the second endpoint is included.
This is: Overweight: (24.9, 29.9]. It is a half-open half-closed interval (relate with Mathematics)
Teacher: Do you know why this would be a problem if the programmer does not fix these issues before developing the calculator?
Student: Yes. Because there would not be any interpretation for anyone whose BMI is between $24.9$ and $25$
But, I do see that the BMI information is for values rounded to one decimal place.
Teacher: That is correct.
And we shall develop our calculator to round to one decimal place.
But, it is important we fix the issues.
What if we do not want to round?
Look at the two examples on the CDC website. The BMI values were rounded to two decimal places.
If we developed our calculator to round to two decimal places with the information on those websites "as is"; then we would not have the interpretation and recommendation for those two examples ($24.98$ and $24.96$) because those values are greater than $24.9$ but less than $25$.
Student: That makes sense.
So, the last one: Obese should be BMI greater than $29.9$, rather than greater than $30$?
Teacher: That is correct.
Let us apply what we learned so far.
We shall develop a console application and a desktop application for the Body Mass Index (BMI) calculator.
I do the console application.
You do the desktop application.
We are yet to cover Statements (covered in Module $5$). However, do not worry.
I explained my comments very well. You will understand the comments.
Please ask questions if you do not understand any of the comments.
We shall use part of Module $5$ (Decision-making statements) in the program.
Please review the screenshots and the comments.
(1.) The program should accept user inputs of:
(I.) First name
(II.) Last name
(III.) Weight
(IV. Height
(2.) The program should output the:
(A.) BMI value
(B.) Interpretation
(C.) Recommendation
(3.) The program should address user-input errors of non-positive numbers for the weight and the height.
Inform the user.
Then, exit the program. Do not allow the program to continue.
To exit the program, we use the command: System.exit(0)
And in Java is represented by the double ampersand symbol &&
Or in Java is represented by the double pipe symbol ||
Code:
Student: I have several questions, Mr. C
Teacher: Please go ahead
Student: First Question: Why did you initialize those variables?
The interpretBMI and the adviceBMI...you initialized them to empty quotation marks: ""
Teacher: Good question.
Assume we did not initialize them
We only defined them within the block of code: the If Statement
Then, we want to print them/output them outside the block of code
The program "will not be happy"
Compare it to this scenario.
A student registered to attend a school.
We did not register the front office registration desk.
But we sent the student to a classroom and the classroom teacher registered that student.
The parents come, looking for their child.
Where will the parent go first?
Student: At the front desk of course
Teacher: Good.
The front desk will first keep a record of the student before sending the student to the class.
We have to first assign the string to something before we send it to the blocks of code, and then output it.
We cannot just declare it without an assignment, then send it to a block of code to be used within that block of
code only, and then want to output it outside the block of code.
Does it make sense?
Student: Yes, it does.
But what if we do not want to print the value outside the block of code?
What if we want to print the value inside each block of code where it is used?
Teacher: I am impressed by your questions.
Yes, we can do that.
But you know what that means...right?
Student: We have to write it each time for each of the conditional statement.
Teacher: That is correct.
Student: Second Question: How did you get the blue color for the heading on the console window?
Teacher: Console Log Formatting:
You can find the commands on my website: American Standard Code for Information Exchange (ASCII)
We have done several console applications.
Now onto desktop applications.
Let us apply the knowledge we acquired in this module to develop a desktop application.
Which application comes to mind right away...a desktop application that deals with Numbers and Operators?
It's the Standard Calculator. Let's develop it. 😊
Please review the desktop applications we developed in previous modules beginning from Module $1$
Let us begin with the desktop calculator on your Windows PC/Laptop
Please see the screenshots
Let us develop the function buttons as seen in the red rectangle.
We are yet to cover Statements (covered in Module $5$). However, do not worry.
I explained my comments very well. You will understand the comments.
Please ask questions if you do not understand any of the comments.
We shall use part of Module $5$ (Decision-making statements) in the program.
JFrame Form: Adjust and Align
title property: Standard Calculator © 2021 SamDom4Peace Designs
Palette | Property |
---|---|
Panel Adjust and Align to cover entire JFrame Form |
background: RGB → Color Code: FFF5EE (This is for the color: SeaShell) font: Font: Times New Roman; Font Style: Plain; Size: 24 Change Variable Name: calculatorPanel |
Label: Adjust and Align |
border: Etched Border (do this first) text: Delete jLabel1 horizontalAlignment: RIGHT (because we want to align the $0$ to the right) font: Font: Times New Roman; Font Style: Plain; Size: 24 border: Etched Border Change Variable Name: calculatorLabel |
Text Field: Adjust and Align |
text: $0$ (because we want $0$ to be the default) horizontalAlignment: RIGHT (because we want to align the $0$ to the right) font: Font: Times New Roman; Font Style: Plain; Size: 24 border: Etched Border Change Variable Name: calculatorTextField |
Button: Adjust and Align |
text: $1/x$ font: Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB → Color Code: FFFFFF (This is for the color: White) Change Variable Name: reciprocalButton |
Duplicate Button: Adjust and Align |
text: $7$ Change Variable Name: sevenButton |
Duplicate Button: Adjust and Align |
text: $4$ Change Variable Name: fourButton |
Duplicate Button: Adjust and Align |
text: $1$ Change Variable Name: oneButton |
Duplicate Button: Adjust and Align |
text: $+/-$ Change Variable Name: plusMinusButton |
Duplicate Button: Adjust and Align |
text: $x^2$ Change Variable Name: squaredButton |
Duplicate Button: Adjust and Align |
text: $8$ Change Variable Name: eightButton |
Duplicate Button: Adjust and Align |
text: $5$ Change Variable Name: fiveButton |
Duplicate Button: Adjust and Align |
text: $2$ Change Variable Name: twoButton |
Duplicate Button: Adjust and Align |
text: $0$ Change Variable Name: zeroButton |
Duplicate Button: Adjust and Align |
text: $\sqrt{x}$ Change Variable Name: squareRootButton |
Duplicate Button: Adjust and Align |
text: $9$ Change Variable Name: nineButton |
Duplicate Button: Adjust and Align |
text: $6$ Change Variable Name: sixButton |
Duplicate Button: Adjust and Align |
text: $3$ Change Variable Name: threeButton |
Duplicate Button: Adjust and Align |
text: $.$ Change Variable Name: decimalButton |
Duplicate Button: Adjust and Align |
text: $\div$ Change Variable Name: divideButton |
Duplicate Button: Adjust and Align |
text: $\times$ Change Variable Name: multiplyButton |
Duplicate Button: Adjust and Align |
text: $-$ Change Variable Name: minusButton |
Duplicate Button: Adjust and Align |
text: $+$ Change Variable Name: plusButton |
Duplicate Button: Adjust and Align |
text: $=$ Change Variable Name: equalButton |
Duplicate Button: Adjust and Align |
text: Clear Change Variable Name: clearButton |
Duplicate Button: Adjust and Align |
text: Exit Change Variable Name: exitButton |
(1.) Run the code and select standardcalculator.StandardCalculator as the main class.
Close the application and let us code the program.
(2.) In the Design Area, double-click the $1/x$ button.
This leads to the Source Area
Scroll all the way to the top and begin to...
(3.) Write the code.
Let us use a top-down approach. So, let us write the code for each toolbox (Palette tool) in the order as seen in
the Design Area.
Please review the screenshots.
Review the comments.
Design Area
Program Code
Student: Mr. C, you used the same name variable: newNumber for different events.
Is that allowed?
Teacher: Very good observation.
We can do that because we defined that variable locally.
This means that the variable: newNumber is only recognized within that event.
If we use it outside that event, it will result in an error because we did not define it in the class.
Notice that we did not have issues with the variables we defined in the class such as firstNumber
We can use those variables anywhere within the class.
Run the Program
NaN means Not a Number It is not a real number. But it is an imaginary number. It is covered under Complex Numbers in Algebra) This calculator deals with only with real numbers. |
|
Let us design another calcuator using more toolbox controls.
For this calculator:
(1.) We want two textfields for user-input.
The two textfields will receive user-input for two numbers (the operands).
Remember that textfields accept only strings.
But we want them to accept numbers.
We shall define those numbers using the double data type (to accomodate decimals).
Then, we shall convert those numbers as strings so that the textboxes will accept them.
(2.) We want a ComboBox.
The ComboBox will contain a dropdown list of items: the operations.
We shall expand our list of operations. So, this calculator will be more of a scientific calculator.
I shall do some functions.
You do the rest of the functions (just as we did for the Standard Calculator).
(3.) We want four buttons: the Calculate, Clear Some, Clear All, and Exit buttons.
(4.) When we run our program, we want the cursor to be focused on the first textfield.
Then, we want the user to be able to use the Tab key on the keyboard to perform any operation without using a mouse.
This is an important software design concept to accommodate users with disabilities.
It is known as the Tab Order Property.
Once the user enters the first number in the first textbox; move to the ComboBox and select an operation from the
dropdown list and press the Tab key; use the Tab to move to the second textbox (as applicable), enter the second number and
press the Tab key (as applicable); move to the Calculate button and hit the Enter key to get the result.
The Tab Order property controls that ability for the Tab to move in that order.
We shall set the Tab Order properties of the toolbox controls accordingly.
For operations that involve two numbers such as calculating the sum, difference and the like: we want it to be:
$first\;\;number \rightarrow operation \rightarrow second\;\;number \rightarrow calculate$
For operations that involve only one number such as calculating the reciprocal, square root and the like: we want to
disable the second textbox so that the user would not enter a second number.
The Tab Order property determines the order in each pallete tool receives focus when the user presses the Tab key
while an application is running.
The Tab Order property is zero-indexed. This means that the first one begins with a 0, the next one is a 1, the next is a 2
among others.
The Tab Order is set in the order that each pallete tool is added to the form.
It is important to run the GUI (without the code) and use the Tab key to ensure that each palette tool receives cursor
focus accordingly.
If the Tab Order is not set in the way you want it, you can adjust it by moving each tool up or down.
Please review the screenshots.
Recap:
Assume the user is working with only the keyboard (software design to accommodate users who cannot use the mouse)
(1.) When the user runs the application, the cursor focus should be in the first textfield waiting for user input.
The user enters a number and presses the tab key
(2.) The next focus should be the ComboBox waiting for the user to make a selection.
The user selects an operation.
If the operation involves only one number, the second textfield is disabled so the focus moves to the Calculate
button.
The command used to disable the textfield is: TextField.setEditable(false);
As you can see, to disable a TextField; the editable property of the TextField is set to the Boolean value: false
If the operation involves two numbers, the cursor focus moves to the second textfield waiting for the user to enter the
second number. The user enters the second number and presses the tab key.
The next focus would be the Calculate button.
The user presses the ENTER key and the calculation is done. The result is displayed in the textarea: ResultTextArea.
(3.) The user presses the tab key and the focus should be the Clear Some button.
The user presses the ENTER key and the entries in the textfields and the textarea are cleared.
(4.) The user presses the tab key and the focus should be the Clear All button.
The user presses the ENTER key and all entries (all items in the ComboBox) are cleared.
(5.) The user presses the tab key and the focus is the Exit button.
The user presses the ENTER key and the application is closed.
Let us work on the design: the form and the palette tools.
JFrame Form: Adjust and Align
name: frame1 (by default. Leave as is)
title: Scientific Calculator © 2021 SamDom4Peace Designs (Sample)
Font: Times New Roman;
Font Style: Plain;
Size: 24
resizable: Uncheck the box
We unchecked the resizable property of the JFrame Form because we do not want the user
to change the size of the application.
We want the interface to have a consistent look.
Palette Tools | Property |
---|---|
Label: Adjust and Align |
text: First Number: Font: Times New Roman; Font Style: Plain; Size: 24 |
Text Field: Adjust and Align |
Font: Times New Roman;
Font Style: Plain;
Size: 24 text: Delete jTextField1 horizontalAlignment: RIGHT Change Variable Name: FirstNumberTextField |
Label: Duplicate the first label Adjust and Align | text: Operation: |
ComboBox: Adjust and Align |
Change Variable Name: OperationComboBox Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB: Color Code Scientific Calculator: FFFFFF (means the White color) model: Delete Item 1 Item 2 Item 3 Item 4 and for teaching purposes type: Please select an operation Addition (+) [2 numbers] Subtraction (-) [2 numbers] Multiplication (*) [2 numbers] Division (÷) [2 numbers] Modulo (mod) [2 numbers] Exponent (xⁿ) [2 numbers: x is the base; n is the exponent] Log_{x}n [2 numbers: x is the base; n is the number] nth Root of x [2 numbers: x is the radicand; n is the index] Reciprocal (1/x) [1 number] Percent (%) [1 number] Absolute Value (|x|) [1 number] n! [1 number] Tangent in DEG (tan) [1 number] Sine in RAD (sin) [1 number] Cosine in GRAD (cos) [1 number] |
Label: Select the first label and the first text field and Duplicate Adjust and Align | text: Second Number: |
Text Field: Select the first label and the first text field and Duplicate Adjust and Align | Change Variable Name: SecondNumberTextField |
Label: Duplicate the label for the Second Number: Adjust and Align | text: Result: |
Text Area: Adjust and Align |
Change Variable Name: ResultTextArea Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB: Color Code Scientific Calculator: FFFFFF (means the White color) editable: Uncheck the box We unchecked the editable property of the Text Area because we do not want the user to edit the result. Further, we want the user to be able to use the Tab key and move on to the Calculate button. |
Button: Adjust and Align |
Change Variable Name: CalculateButton Font: Times New Roman; Font Style: Plain; Size: 24 background: RGB: Color Code Scientific Calculator: FFFFFF (means the White color) text: Delete jButton and write Calculate Horizontal Size: 160 |
Button: Copy and paste the previous button Adjust and Align |
text: Clear Some Change Variable Name: ClearSomeButton Horizontal Size: 160 |
Button: Copy and paste the previous button Adjust and Align |
text: Clear All Change Variable Name: ClearAllButton Horizontal Size: 160 |
Button: Copy and paste the previous button Adjust and Align |
text: Exit Change Variable Name: ExitButton Horizontal Size: 160 |
A JComboBox
is a palette tool that allows the user to select items from the a list.
(https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html)
It can have two very different forms: the editable Combobox and the uneditable ComboBox.
There are several properties of the ComboBox.
We shall discuss only one property in this module: the SelectedIndex
property.
The SelectedIndex property gets or sets the index of a selected item.
The ComboBox items are zero-indexed just like arrays.
This means that the first item has index: $0$, the second item has index $1$, and the third item has index $2$ among others.
The command used to specify a selected item in the ComboBox is: ComboBox.getSelectedIndex() == Index
Based on the items in the ComboBox in our program:
ComboBox Items | Index |
---|---|
Please select an operation | $0$ |
Addition (+) [2 numbers] | $1$ |
Subtraction (-) [2 numbers] | $2$ |
Multiplication (*) [2 numbers] | $3$ |
Division (÷) [2 numbers] | $4$ |
Modulo (mod) [2 numbers] | $5$ |
Exponent (xⁿ) [2 numbers: x is the base; n is the exponent] | $6$ |
$Log_{x}n$ [2 numbers: x is the base; n is the number] | $7$ |
nth Root of x [2 numbers: x is the radicand; n is the index] | $8$ |
Reciprocal (1/x) [1 number] | $9$ |
Percent (%) [1 number] | $10$ |
Absolute Value (|x|) [1 number] | $11$ |
n! [1 number] | $12$ |
Tangent in DEG (tan) [1 number] | $13$ |
Sine in RAD (sin) [1 number] | $14$ |
Cosine in GRAD (cos) [1 number] | $15$ |
(1.) Click the Source Area.
Scroll a little bit to the top, write the comments, and begin to...
(2.) Write the code.
What should happen when the user clicks the Calculate button?
Please review the screenshots.
Review the comments.
Design Area
Program Code
To clear all the items in a ComboBox, we use the command: ComboBox.removeAllItems();
Student: Mr. C, you used these variables: firstNumber, secondNumber, result for different events.
Is that allowed?
Teacher: Very good observation.
Yes, we can do that.
Here is the reason: we used it within each event (each conditional statement).
We defined it as a class member variable. But remember we did not specify any value for it.
Hence, we are free to use it as local variables.
We can use those variables anywhere within the class.
But you are very welcome to use different variables for the different events if you choose.
Run the Program
For Questions (1.) and (2.); please review the other Java operators
(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html)
Using code examples and well-written comments for each operator, discuss any of these operators.
(1.) Conditional Operators
(2.) Bitwise and Bit Shift Operators
(3.) Visit my website on Numbers
(www.numbersandnotations.appspot.com/numbers.html)
Choose any applicable question and write a Java program to solve it.
Please make sure that the output of your program gives the same result as the solution of the
question on my website.
You may use Arithmetic Operators, Math Functions, or both.
(4.) Visit my website on Percent Applications
(www.fractions-decimals-percents.appspot.com/percentApplications.html)
Choose any applicable question and write a Java program to solve it.
Please make sure that the output of your program gives the same result as the solution of the
question on my website.
You may use Arithmetic Operators, Math Functions, or both.
(5.) Program to determine your age
***Because your age is a PII (Personal Identifiable Information), you may use a fictitious age.
However, you need to test it (privately) with your actual age to make sure it works.***
Develop a Java program to determine your age based on these instructions.
ONLY one variable is required.
(Hint: If only one variable is required, this implies that you need to use Compound
Assignment operators)
The user wants you to note that these instructions would only work for ages determined this
year, and wants you
to specify it in the program.
(a.) Pick an integer between $0$ and $10$ ($0$ and $10$ exclusive).
(b.) Multiply the integer by two.
(c.) Add five to the result.
(d.) Multiply the result by fifty.
(e.) If you already had your birthday this year, add the result to one thousand, seven hundred
and seventy-two.
If you have not had your birthday this year, add the result to one thousand, seven hundred
and seventy-one. (valid for 2022, adjust accordingly after 2022)
(f.) Subtract your four-digit birth year from the result.
Run the code and display the output.
Explain your result.
(6.) A client wants you to develop a program to calculate the age of his child.
The instruction for the previous question still applies to this question.
However, in this case; the program will give the instructions to the child, and the child will
respond.
This program is an Input/Output program.
Develop a Java program for this child.
(7.) Program to determine your date of birth.
***Because your date of birth is a PII (Personal Identifiable Information), you may use a
fictitious age. However, you need to test it (privately) with your actual age to make sure it
works.
Develop a Java program to determine your date of birth based on these instructions.***
ONLY one variable is required.
(Hint: If only one variable is required, this implies that you need to use Compound
Assignment operators).
(a.) Pick the integer that is your month of birth.
(b.) Multiply the integer by two hundred.
(c.) Add three hundred and eighty two to the result.
(d.) Divide the result by two.
(e.) Add your day of birth to the result.
(f.) Multiply the result by 100.
(g.) Add thirteen thousand, eight hundred and forty to the result.
(h.) Add the last two digits of your year of birth to the result.
(i.) Subtract thirty two thousand, nine hundred and forty from the result.
Run the code and display the output.
Explain your result.
(8.) A client wants you to develop a program to calculate the date of birth of her child.
The instructions for the previous question still applies to this question.
However, in this case; the program will give the instructions to the child, and the child will
respond.
This program is an Input/Output program.
Develop a Java program for this child.
(9.) Develop a Body Mass Index (BMI) desktop application using the United States System.
Test each condition just like we did in our example for the United States System.
Address user-input errors.
(10.) Develop a Body Mass Index (BMI) console application using the International System.
The formula is on the screenshot.
Test each condition just like we did in our example for the United States System.
Address user-input errors.
(11.) Develop a Body Mass Index (BMI) desktop application using the International System.
The formula is on the screenshot.
Test each condition just like we did for the United States System.
Address user-input errors.
Questions (12.) and (13.) are meant to prepare you for the Midterm Project.
For Questions (12.) and (13.)
Develop a VB program that meets these requirements.
(I.) Consider any concept/scenario that uses conditional statements.
It will be great if you find a real-world application. However, you can make up your own.
If you decide to make up your own, please explain the scenario and the conditions well.
If you use a real-world application, please cite your source(s) accordingly. Explain the scenario and the conditions well.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Address user input errors.
(IV.) Test your program and display the result/output for each condition.
(V.) Test your program for user-input errors.
(VI.) Submit all the screenshots accordingly.
(12.) Develop a console application for your concept.
(13.) Develop a desktop application for your concept.
Textbook Questions
(14.) Question $12$ on Page $107$
(15.) Question $14$ on Page $107$
(16.) Question $16$ on Page $107$
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) Java Math: Exercises, Practice, Solution
(B.) Java Basic Programming - Part 1: Exercises, Practice, Solution
(C.) Java Basic Programming - Part 2: Exercises, Practice, Solution
(D.) Java Data Types: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(17.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for Java
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for java programmer, you might be surprised that even for entry level positions
for a Java Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with Java.
However, if you find out that C# would be better in solving a particular problem in your workplace,
then you need to use C# unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in Java and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in Java and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C# Basic Declarations and Expressions : Exercises, Practice, Solution
(B.) C# Basic Algorithm: Exercises, Practice, Solution
(C.) C# Data Types : Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(18.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C++ Basic: Exercises, Practice, Solution
(B.) C++ Basic Algorithm: Exercises, Practice, Solution
(C.) C++ Math: Exercises, Practice, Solution
(D.) C++ Numbers: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(19.) Please focus only on Questions that deals with Numbers and Operators.
Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
(1.) Provide any of these if it is lacking in any DB post that solved any question in the
Assess tab of this module: Well-written comments; another approach/method to solving the
question; any additional relevant details; etc.
For Questions (5.) and (6.) in the Substantive Posts
Student: Mr. C, the instructions in Questions (5.) and (6.) are not correct.
The result is not my age.
How can you ask us to write a program that does not work?
(2.) Explain the result to the Student. (Answer this question only if any of your colleagues made a similar statement in the initial post.)
(3.) The Student wants only his/her age to be the result.
Without modifying any of the instructions (but using all of them) and one more instruction, extend the
program to display only the Student's age.
What is the extra instruction that you would include to work for all ages?
Write it. Run it. Submit clear screenshot(s).
For Questions (7.) and (8.) in the Substantive Posts
Student: Mr. C, I want the date of birth to display properly.
Teacher: Use a delimiter.
Student: What is a delimiter?
Teacher: A delimiter is a sequence of chararcters that specifies limits/boundaries of characters
in a text, expression, word, etc.
A good example is the forward slash that you can use to separate that DOB in the form of: mm/dd/yyyy.
The forward slash is a delimiter.
Another example is the pipe delimiter: mm | dd | yyyy.
Another example is the hyphen delimiter: mm-dd-yyyy.
Student: Okay, how do I display the result in that format?
(4.) Explain how you would display the result for the Student.
Write the code. Run it. Submit clear screenshot(s).
(5.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(6.) Other substantive responses.
This is the NumbersOperators.jar Standard Calculator
(1.) Please review the Functionalities of the Calculator and the Limitations of the Calculator as explained in
the Learn tab.
Maintain all the functionalities of the calculator.
Address the first three limitations.
You may use my code if you wish
(in this case because you are extending the functionalities of my program) and/or your code.
(2.) The first standard calculator we programmed did not contain all the functions.
This is what we did.
This is what you should do.
Develop a calculator that contains all the functions.
Due the scope of this module, you may work with only the integer data type.
However, your calculator should handle quotients that are decimals (division of integers that results in decimals)
Your calculator should also handle percentages (for those integers whose percentages gives decimals).
Because you are working with only integers, you may remove the decimal function button and replace it with any
function you prefer.
Please note:
The C function is the Clear function. It deletes everything.
It clears the first number, operation, and the second number.
The CE function is the Clear Entries function. It deletes "some" things.
It clears only the second number. You can replace the second number and continue with the calculation.
It does not clear everything.
This is used when the entire calculation does not need to be deleted.
The BS (backspace) function (you may use alt+174 key if you prefer) is the backspace function.
It deletes part of the first number or the second number.
This is also used when the entire calculation does not need to be deleted.
Let us look at an example. You may test it.
$
\underline{Example} \\[3ex]
25 + 32 \\[3ex]
\color{red}{C} \;\; deletes\;\;everything \\[3ex]
\color{red}{CE} \;\; deletes\;\;only\;\;32 \\[3ex]
\color{red}{BS} \;\; deletes\;\;only\;\;2 \\[3ex]
$
This is the executable Numbers.jar Scientific Calculator
(3.) We developed the scientific calculator.
However, it does not contain all the functions.
Develop the scientific calculator GUI that contains all the functions.
You may extend my application by adding the missing functions if you wish, or you may develop your own with all the functions.
You may use my Code Scientific Calculator if you wish
(in this case because you are extending the functionalities of my program) and/or your Code Scientific Calculator.
(4.) Develop a console application for an extension of the Body Mass Index (BMI) application example.
We did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
This is the BodyMassIndexApplication.jar executable file
You may click the link to download and run it. No worries, it is safe.
It is a desktop application.
If you have Java on your computer (PC or Mac desktop/laptop), click the file and run the application directly on your desktop.
(5.) Develop a desktop application for an extension of the Body Mass Index (BMI) application example.
We did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Your desktop application should have the dropdown list for both systems, but should be null be default (using a ComboBox)
Alternatively, you may choose to use Radio Buttons.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
Question (6.) is meant to prepare you for the Midterm Project.
Develop a VB program that meets these requirements.
(I.) Consider any concept/scenario that uses conditional statements.
A real-world application is required. You may not make up your own.
Please cite your source(s) accordingly. Explain the scenario and the conditions well.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Address user input errors.
(IV.) Test your program and display the result/output for each condition.
(V.) Test your program for user-input errors.
(VI.) Submit all the screenshots accordingly.
(6.) Develop a console application and a desktop application for your concept.
character, string, Boolean, bool, function, argument, dot member access operator, concatenator operator, string literal, empty string, date, time
Students will:
(1.) Discuss the Java string data type.
(2.) Discuss the Java Boolean data type.
(3.) Discuss Date and Time in Java.
(4.) Write programs that involves the String data type.
(5.) Write programs that involves the Boolean data type.
(6.) Write programs that involves Date and Time.
(1.) Textbook Chapter
(2.) Java Strings and Java Booleans
(Java Strings: www.w3schools.com/java/java_strings.asp) and (Java Booleans: www.w3schools.com/java/java_booleans.asp)
(3.) Java SE 8: Getting Started with String Processing: Invoking the String Class Methods
(Java SE 8: Getting Started with String Processing: Invoking the String Class Methods: www.oracle.com/webfolder/technetwork/tutorials/obe/java/String/String.html#section2)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type Java Strings and/or Java Booleans and/or Java Date and Time in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type Java Strings and/or Java Booleans and/or Java Date and Time in the search bar and view/read the results.
A String is a sequence of ordered characters.
It is built out of characters.
It is enclosed in matching single or double quotation marks.
Remember the first Java program we wrote, the output...the message, THANK GOD.
That is an example of a string.
Let us review more examples of what we could do with Java strings.
Join strings.
Let us discuss several ways of joining strings.
Please review the screenshots and the comments.
First Approach: Concatenator operator
Teacher: There is an issue here.
Student: There is no space between your first and last name.
Teacher: That is correct.
How do we fix it?
Student: Include a space between the names.
Teacher: There are several ways we can do this.
We can include an empty string in between the names.
Join two strings using Concatenation operator (Space included between the strings)
Teacher: We can also use the StringBuffer class with the Append method
The Append method does not automatically include a space between the strings.
So, we have to include the space appropriately.
Second Approach: StringBuffer class with the Append method
Student: In the Second Approach: StringBuffer class with the Append method
You did not use the string variables: firstName and lastName
Teacher: That is correct.
Student: What if I want to use the string variables with the append method?
Instead of using strings?
Do you understand what I mean?
Teacher: I do.
Nice question.
We can do it.
We shall have the variable: firstName as the argument of the object
We append an empty string
Then, we append the lastName.
Student: So, we can use two append methods with a string?
Teacher: Yes.
We shall use those append methods accordingly with the dot member access operator (the period, .)
Let us do this with the Third Approach.
However, you can still do it with the Second Approach.
But, let us see another approach.
Third Approach: StringBuilder class with the Append method
Student: What is the difference between the StringBuffer class and the StringBuilder class?
Which one should we use?
Teacher: Good question.
We shall discuss the differences in Advanced Java course.
But, I prefer you use the StringBuilder class because it is more efficient than the StringBuffer class.
However, it depends on what you want to do with the string.
We shall discuss the String class, the StringBuffer class, and the StringBuilder class in Advanced Java course.
Escape Sequences
An escape sequence is a character preceded by a backslash (\)
Escape Sequence | Description |
---|---|
\t | Insert a tab space |
\b | Insert a backspace |
\n | Insert a new line |
\r | Insert a carriage return |
\f | Insert a formfeed |
\' | Insert a single quote |
\" | Insert a double quote |
\\ | Insert a backslash |
Backslash Escape Sequence, \
Sometimes, we write sentences that has the single quotation marks and the double quotation marks.
How do we display these sentences in a Java program?
We have to use the backslash escape sequence
It turns special characters into string characters.
Please review the screenshots and the comments.
Insert single quote, double quote, backslash in sentences
Teacher: I do not want to scroll all the way to the right to see the entire results.
What should I do?
Student: Insert a new line?
Teacher: That is correct....insert a new line escape sequence.
The third quote: the quote by St. Jerome is okay.
But, let us add new lines to the first quote: the quote by St. Francis of Assisi and the second quote: the quote by
Maya Angelou.
In the previous module, we reviewed some examples of the Input/Output with Numbers.
In this module, let us demonstrate the Input/Output feature with Strings.
As we did with Numbers, we have to import the Scanner class of the java.util package
Input/Output Feature with Strings
Teacher: What are you looking at?
You already know.
Student tries to hide it.
Teacher: I want to ask you something.
Look at it.
Please turn it off...remember the course syllabus.
Before you turn it off, do you see two numbers in the Power off button?
Student: Numbers?
I do not see numbers.
It's an icon.
Teacher: Yes, they are numbers.
The numbers are: $0$ and $1$
$1$ is inside the $0$ in most devices.
Student: Interesting.
Teacher: $0$ represents OFF
$1$ represents ON
You see these two numbers in almost all electronic devices (tablets, smartphones, computers) including some
electric switches.
In Logic, $0$ represents FALSE
$1$ represents TRUE
We use true and false Boolean values in Statements including conditional statements and
iterative statements. We shall cover Statements in the next module.
The use of these two numbers: $0$ and $1$ in Mathematics and Computer Science to repesent FALSE and
TRUE values is known as Boolean Algebra
It was developed by George Boole, an English mathematician/philospher/logician.
We can also use these Boolean numbers $0$ and $1$ to represent choices/options of NO and YES
A Boolean is a fundamental data type in Java that:
(1.) is declared with the keyword, bool
(2.) can represent only one of two states: true or false
(3.) gives an output of only one of two values: true or false
(4.) is used for comparison (in relational and comparison operators) to compare expressions.
(5.) is used in statements (conditional statements and iterative statements) to make decisions.
A Boolean Expression is an expression that returns a Boolean value.
Let us demonstrate some examples of the use of Booleans.
Booleans: Example 1
Booleans: Example 2
Date and time stamps are needed for: transactions, receipts, appointments, agreements, events, rules/laws, and
tickets (by cops and troopers) among others.
Besides, we shall use the date and time functions in the midterm project.
Let us discuss date and time.
Teacher: The date and time is interesting in the sense that I would not classify it as a string or as an
integer.
Student: What data type would you call it?
Teacher: It is a data type by itself.
However, you can treat it as a string and use certain string functions with it.
You can also treat it as an integer by adding or subtracting days and years.
There are several approaches to display date and time in Java.
Let us discuss two appraches.
First Approach: java.time package
To display date and time in Java, we need to import the java.time package.
The java.time package includes several classes to access date and time.
Some of the classes included in the java.time package are:
(1.) LocalDate: This displays the date in the format: yyyy-MM-dd (year, month, day format)
(2.) LocalTime: This displays the time in the format: HH-mm-ss-ns (hour, minute, second, nanosecond
format)
(3.) LocalDateTime: This displays the date and time in the format: yyyy-MM-dd-HH-mm-ss-ns (year,
month, day, hour, minute, second, nanosecond format)
These classes use the now() method to get the current date and time.
(4.) DateTimeFormatter: This uses the ofPattern() method to format the date and time objects and
display them in several formats.
However, we have to create a String variable that formats the LocalDate or LocalTime or LocalDateTime object with
the object of the DateTimeFormatter using the .format method.
Please review the screenshots and the comments.
Date and Formatted Date
Time and Formatted Time
Date and Time, and Formatted Date and Time
Let us review more approaches to handling date and time in Java
Date, Time, and Time Zone
We need to import the Date class of the java.util package
Format the Date, Time, and Time Zone
We need to import an additional class: the DateFormat class of the java.text package
As at today: 03/01/2021; Kent State University has 8 Ohio campuses, several other U.S campsuses, and four campuses
outside
the United States otherwise known as Kent State Worldwide.
Kent State Worldwide consists of Kent State in Florence, Italy; Geneva, Switzerland; New Delhi, India; and Beijing,
China.
Mr. C wants to greet all his students in the United States and Worldwide.
He wants to great them in their local dates and times.
He would kindly ask you, his student (please check out one of the Questions in the Assess tab) to teach him the greeting
in your language.
But his work right now is to display the date and time of each country: United States, Italy,
Switzerland, India, and China.
Because we shall be working with foreign countries, we need:
(1.) Time zone of each
country.
TimeZone represents a time zone offset, and includes daylight savings.
As at today: 03/04/2021; the time zone IDs that are available in Java are:
Note that these time zone IDs should be entered as strings.
If the country is not listed, then we will need to use the UTC (Universal Time Coordinated) and include any offset
as applicable.
How?
Bing or Google "time zone for country" and look for the UTC time zone of that country.
If it is UTC+4, then use UTC+4 for that time zone. It should work in Java.
Alternatively, contact Oracle and ask them to include your country/city/county/province/region.
(2.) Current date and time (date and time now) of each country.
(3.) Locale of each
country.
A Locale object represents a specific geographical, political, or cultural region.
Typically, it has three arguments though it can take one or two arguments.
We shall use the Locale object with two arguments as:
Locale dateTimeCountry = new Locale("language", "countryCode");
This is the
List of Countries, Languages, and Locale for Displaying Date and Time
(https://www.samdomforpeace.com/References/ASCII.html#specificCulture)
(4.) Necessary packages: As we write our code, the necessary classes of the Java packages will be added (imported)
to the code.
If they are not, we will have to add them manually.
Please Explore
That is one of the ways to learn the Java programming language well.
The DateTimeFormatter class has several methods.
I encourage you to explore the methods so you see the several formats that you can use for the date and time.
Please explore the methods of the other classes that we used.
Type the class such as: DateTimeFormatter and then type the dot access member operator (the decimal point on
your keyboard) and you will see the methods.
Have fun exploring 😊
Please review the screenshots and the comments.
Date and Time: Example 1: Current Date and Time in Different Countries
Student: What if we want to display the date and time in several states across the United States?
Our students come from all 50 states of the United States as well as the United States territories.
And you know there are different time zones in the United States.
How do we display the current date and time in those states in their respective time zones?
Teacher: Very good question.
Say we want to find the date and time in the State of Alabama.
The State of Alabama is in the Central time zone. The time is Central Standard Time (CST)
First, we get the ZoneId of the time zone.
ZoneId timeZone = ZoneId.of("US/Central");
Then, we get the current date and time based on that time zone.
ZonedDateTime stateAlabamaDateTime = ZonedDateTime.now(timeZone);
Then, we create an object of the Locale class and use the specific culture as the parameter.
Locale dateTimeAL = new Locale("en", "AL");
Then, you complete it accordingly...just as we did in the Example $1$
This is the List of the States and Territories of the United States for Displaying Date and Time
(https://www.samdomforpeace.com/References/ASCII.html#specificCultureUS)
Let's develop another date and time function application.
What are some of your memorable events? dates for those events?
Student: Birthday, Christmas...I'm always looking forward to it
Teacher: Let's write a program in that regard.
I shall use my birthday as an example.
Let us calculate how many days there are until my birthday.
We shall begin with a console application.
Then we shall develop a desktop application and explore more toolbox controls.
An interesting toolbox control to explore is the Timer.
Have you noticed those websites where you see a timer that displays a countdown of the times:
days:hours:minutes:seconds
to a particular event?
Student: Yes, I have.
Teacher: Cool. So, we shall explore that control and some other controls for the GUI.
As at today: 03/02/2021, my birthday is yet to occur. However, it is important to add a functionality to the
program to display a message to the user if the user's birthday has already occurred prior to today.
Student: I guess we shall ask the user to enter the birthday?
Teacher: Yes. Let's use an Input/Output feature to make it interactive.
The program will ask the user to enter the birth year, birth month, and birth day.
If the birthday has already occurred, inform the user accordingly. Then, display a positive message informing
the use that we look forward to his/her next "age" birthday.
If the birthday is yet to occur, display the number of days remaining until the birthday.
If the user's birthday is today, we shall greet the user with a HAPPY BIRTHDAY greeting.
This will require a conditional statement.
Student: You know Mr. C, we have been using Statements since Module 3 when we are supposed to cover it in
Module 5.
Teacher: That is correct. It goes to show how important they are in programming.
It is okay to introduce you to them so you get familiar with using them.
We shall cover them in detail in Module 5. It is a broad topic.
Please review the screenshots and the comments.
Date and Time: Example 2: Birthday Application
You may use strings not written in English language. However, if you use any language other than English language,
please make sure you translate it. Your colleagues and I need to understand any language you use.
Insensitive words or any word deemed inappropriate to any race, gender, religion, and national origin among others are unacceptable.
Any violation will not yield any point.
If you are not sure of the words/string to use, please contact me first.
Remember DB 3 Requirement. There are enough methods for everyone. If all the methods are done, please
attempt another question.
Please review the:
Java String methods by W3Schools
(www.w3schools.com/java/java_ref_string.asp) and/or
Java String methods by Beginners Book
(www.beginnersbook.com/2013/12/java-strings/) and/or
Java String methods by Oracle
(https://docs.oracle.com/javase/9/docs/api/java/lang/String.html)
(Scroll down till you see the tab: All Methods)
(1.) Review the methods and the examples.
Pick any five methods besides the ones I discussed.
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
Please review the:
Java StringBuffer class by Tutorialspoint
(www.tutorialspoint.com/java/lang/java_lang_stringbuffer.htm) and/or
Java StringBuffer class by Oracle
(https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html)
(Scroll down till you see the tab: Method Summary)
(2.) Review the methods and the examples.
Pick any five methods besides the ones I discussed.
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
Please review the:
Java StringBuilder class by Tutorialspoint
(www.tutorialspoint.com/java/lang/java_lang_stringbuilder.htm) and/or
Java StringBuilder class by Oracle
(https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
(Scroll down till you see the tab: Method Summary)
(3.) Review the methods and the examples.
Pick any five methods besides the ones I discussed.
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
Textbook Questions
(4.) Question (2.) on Page 362
(5.) Question (4.) on Page 362
(6.) Question (6.) on Page 363
(7.) Please review the Date and Time example in this module.
Our students come from the entire 50 states of the United States and its territories.
However, the United States has different time zones.
Find out/browse/learn/discover the different time zones in the United States and its territories as seen in the
The Official U.S. Time (https://time.gov/) according to the
National Institute of Standards and Technology
Include those time zones in your comments.
Display the current date and time for each time zone.
Verify your answer with the times and time zones on that website.
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) Java Strings: Exercises, Practice, Solution
(B.) Java Date and Time: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(8.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for Java
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for java programmer, you might be surprised that even for entry level positions
for a Java Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with Java.
However, if you find out that C# would be better in solving a particular problem in your workplace,
then you need to use C# unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in Java and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in Java and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C# Strings : Exercises, Practice, Solution
(B.) C# Date and Time: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(9.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
(A.) C++ Strings: Exercises, Practice, Solution
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(10.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different string method to work on the same string used by your colleague.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
You may use strings not written in English language. However, if you use any language other than English language,
please make sure you translate it. Your colleagues and I need to understand any language you use.
Insensitive words or any word deemed inappropriate to any race, gender, religion, and national origin among others are
unacceptable. Any violation will not yield any point.
If you are not sure of the words/string to use, please contact me first.
(1.) We are yet to do Statements (in the next Module), but you can give this question a try.
A string palindrome is a word, phrase, clause or sequence of characters that is
spelled and read the same way backward and forward.
In other words, when one reads it as is, reverses it and reads it again; the pronunciation is the same.
Examples include the:
Words: HANNAH, BOB, madam, level, civic, racecar, rotor
Phrase: never odd or even
Clause: nurses run
Sentence: Was it a car or a cat I saw?
Write a Java program that asks for user input.
Determine if the user input is a string.
If the user input is not a string, ask the user to enter only a string.
If the user input is a string, determine if it is a string palindrome.
Inform the user whether it a string palindrome or not.
Test at least one example of: Words, Phrase, Clause, and Sentence that was listed.
This implies that you should test at least four examples.
(2.) Please review the Date and Time: Example 1: Current Date and Time in Different Countries
Extend my application by greeting your fellow colleagues in the langauge of their countries.
Due to the nature of the Hindi and Chinese alphabets, do not worry about India and China.
Write a Java application that:
(a.) Displays the date and time for the countries: United States, Italy, and Switzerland.
Because you are extending my application, you may use my code.
Find out/browse/learn/discover the greetings for Good Morning, Good Afternoon, and Good Evening for Italy and
Switzerland in Italian and German respectively.
(b.) Displays the greetings to each user (your fellow colleague) according to the current time.
If the time is between 12:00:01 AM to 12:00:00 PM (inclusive), greet Good Morning in each langauge.
If the time is between 12:00:01 PM to 04:00:00 PM (inclusive), greet Good Afternoon in each lanaguage.
If the time is between 04:00:01 PM to 12:00:00 PM (inclusive), greet Good Evening in each language.
Explore the time formats of the DateTimeFormatter class or any other applicable Java class.
You may use 12-hour or 24-hour time formats.
These are the minimum requirements. You are welcome to add more functionalities.
(3.) Please review the Date and Time example in this module.
Our students come from the entire 50 states of the United States and its territories.
However, the United States has different time zones.
Find out/browse/learn/discover the different time zones in the United States and its territories as seen in the
The Official U.S. Time (https://time.gov/) according to the
National Institute of Standards and Technology
Include those time zones in your comments.
Display the current date and time for each time zone.
Greet each user (your fellow colleague) according to their time zones (their own current times).
If the time is between 12:00:01 AM to 12:00:00 PM (inclusive), greet Good Morning.
If the time is between 12:00:01 PM to 04:00:00 PM (inclusive), greet Good Afternoon.
If the time is between 04:00:01 PM to 12:00:00 PM (inclusive), greet Good Evening.
You may use 12-hour or 24-hour time formats.
These are the minimum requirements. You are welcome to add more functionalities.
(4.) Please review the Date and Time: Example 2: Birthday Application
Modify my application or write your new application.
(a.) Ask the user to also enter the time (hh:mm:ss) in hours, minutes, and seconds that he/she was born.
(b.) If the user has not had birthday this year, inform the user about the number of days, hours, minutes, and seconds
until his/her birthday.
Do not stress about the calculations. Java has classes and methods that handle most of these calculations.
(c.) If the user already had birthday this year, or if today is the user's birthday; display appropriate positive
messages to the user.
(d.) A user's birthday is 29th February. This implies that the user has to celebrate birthdays only on leap years
(years that are divisble by 4). Accommodate that user in your application. Display message(s) accordingly.
(e.) Include checks for user-input errors and display messages accordingly.
(5.) Write a Java program that solves Question (8.) on the
Applications of Numbers website.
(https://numbersandnotations.appspot.com/numbersApplications.html)
Use any actual date that is a Tuesday.
Ensure that the output of your program corresponds to the solution on the website.
Please display: the actual date, the actual day, the new date and the new day in your output.
In other words, I am looking for the input date, the input day that is a Tuesday, the output date, and the output day
that is a Friday.
Please check to ensure your program gives the correct output (result).
You may develop a console application or a desktop application for this program.
Submit screenshots of the question, your program, and the output of your program.
(6.)
statement, expression, block, expression statement, assignment statement, increment and decrement statements, method invocation statement, object creation statement, declaration statement, control flow statement, decision-making statements, conditional statements, decision, selection statements, looping statements, branching statements, branches, repetitive statements, iteration statements, loops, for loop, while loop, do-while loop, for-each loop, jump statements, break, continue, ternary operator
Students will:
(1.) Discuss Statements in Java programming language.
(2.) Write decision-making statements.
(3.) Write looping statements.
(4.) Write branching statements.
(5.) Write programs that solve real-world problems using statements.
(6.) Complete the Midterm Project on Piecewise Functions.
(1.) Textbook Chapter
(2.) Expressions, Statements, and Blocks
(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html)
Begin from Expressions, Statements, and Blocks to Questions and Exercises
(3.) Java If...Else
(www.w3schools.com/java/java_conditions.asp)
Begin from Java If...Else to Java Break/Continue
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type Java Statements in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type Java Statements in the search bar and view/read the results.
Expression
An expression is a construct made up of variables, operators, and method invocations, which are constructed
according to the syntax of the language, that evaluates to a single value.
// Expression
// We covered this statement in Module 3
double result = 7 * (5 - 2); // 21
Statement
A statement is an individual instruction of a program.
It ends with a semicolon.
It forms a complete unit of execution.
It is equivalent to a sentence in a language.
There are three kinds of statements in Java.
They are:
(1.) Expression Statements
These are statements that are made from expressions.
They include:
(I.) Assignment statement
// Assignment statement
// We covered this statement in Module 3
int num1 = 7;
(II.) Increment and Decrement statements
// We covered this statement in Module 3
// Increment statement
num1++;
// Decrement statement
num1--;
(III.) Method invocation statement
// Method invocation statement
// We have been using this statement since Module 1
System.out.println("THANK GOD");
(IV.) Object creation statement
// Object creation statement
// We used this statement in Modules 3 and 4
import java.util.Scanner; // Import the Scanner class of the java.util package
// Create the object: userInput of the Scanner class
Scanner userInput = new Scanner(System.in);
(2.) Declaration Statements
A declaration statement declares a variable.
// Declaration statement
// We covered this statement in Module 3
int num1 = 7;
(3.) Control Flow Statements
Generally, statements in Java are executed from top to bottom, in the order that they appear.
However, control flow statements control the order in which statements are executed.
In other words, they break up the flow of the execution of statements by using decision making, looping, and
branching; thereby allowing a program to execute particular blocks of code conditionally.
They include:
(I.) Decison-making Statements
The decision-making statements are the: if statement, if-else statement, if-then statement,
if-then-else statement, Multiple ifs statement, and the switch statement
These statements are also referred to as Conditional statements or Decisions or Selection statements
(II.) Looping Statements
The looping statements are the: for loop, while loop, the do-while loop, and the for-each loop
These statements are also referred to as Repetitive statements or Iteration statements or Loops
(III.) Branching Statements
The branching statements are the: break statement, continue statement, and the return statement
These statements are also referred to as Jump statements or Branches
Block
A block is a group of zero or more statements between balanced braces that can be used where a single statement is allowed.
In Example 3 (If-else statement) as seen in the screenshot below; the if statement is the
first block of code and the else statement is the second block of code.
Decision-making statements are statements that execute an action based on some condition(s).
They are also known as Conditional Statements or Decisions
These statements are the:
(1.) If statement
This statement is used when there is only one condition.
If some condition is met, execute a given task.
The If statement is written as:
if (condition) { statement; }Java ignores whitespaces so you can also write it this way:
if (condition) { statement; }
if (condition) { statement; } else { statement; }Java ignores whitespaces so you can also write it this way:
if (condition) { statement; } else { statement; }We can also write simple If-else statement using the Ternary operator
variable = if (condition) ? statement if true : statement if false;(3.) If-else if-else statement
if (condition 1) { statement; } else if (condition 2){ statement; } else if (condition 3) { statement; } else { statement; }Whitespaces are ignored in Java. Therefore you can also write it this way:
if (condition 1) { statement; } else if (condition 2) { statement; } else if (condition 3) { statement; } else {statement; }Keep in mind that we do not specify condition 4 in the code for the else statement because we already know that the else statement would only be executed if all the other prior conditions are not met.
if (condition 1) { statement; } if (condition 2){ statement; } if (condition 3) { statement; } if (condition 4) { statement; }Whitespaces are ignored in Java. Therefore you can also write it this way:
if (condition 1) { statement; } if (condition 2) { statement; } if (condition 3) { statement; } if (condition 4) { statement; }Review the Definitions of Numbers
A good application of Java Selection Statements is seen in Piecewise functions.
Please review the
Story on Piecewise Functions
(www.piecewise-functions.appspot.com/#story)
Let us write several Java programs that will solve the Piecewise function problem in that story.
Piecewise Function: Selection Statements using Multiple Ifs statements
Conditional Statements: Example 8 (Multiple conditions: Multiple ifs)
Let us address user-input errors for the number of burritos that may be out of range in the Piecewise Function.
It is important to address user-input errors in any program you write.
In this case (for the Story on Piecewise Functions): the program will not display any output if the user enters a negative
number, a zero, or any positive number greater than the upper bound of the last piece.
The user may then be confused if he/she does not see any output.
We want to avoid that.
In the case of user-input error, we want the program to display a message that the user entered something out of range, and
then exit without interrupting the system.
Hence, we wrote the message for the user and included the System.Exit(0); method to exit the program.
What if the user enters $2500$?
What if the user enters $-3$?
Student: Can we write the same Piecewise function using the If-else if-else statements?
Teacher: Nice question.
What do you think?
Student: I think we can.
Teacher: Yes but we need to include the last else statement
Student: Must we include it?
Teacher: Highly recommended...yes
However, the program will work even if we do not include it.
But my recommendation is that whenever you use if-else statement, make sure you include the last else statement
In this case (using the if-else if-else statement), the last elsestatement will have a statement but not a
condition.
It is executed when all prior conditions are not met.
So, let us write a statement that will display the message to the user if the user enters any value that is out of range.
using the If-else if-else statements
Piecewise Function: Conditional Statements using If-else if-else statements
Conditional Statements: Example 9 (Multiple conditions: If-else if-else statements)
What if the user enters $0$?
What if the user enters $3000$?
What if the user enters $-12$?
Teacher: Did you notice the importance of that final else statement?
We did not need to specify the range of numbers that are out of bounds as we did for the Multiple Ifs statements.
(5.) Switch statement
Another selection statement is the switch statement.
It works with the: byte, short, char, and int primitive data types and the String class.
It also works with the enumerated types (discussed in Enum Types), and a few special classes that wrap certain primitive
types: Character, Byte, Short, and Integer.
The body of a switch statement is known as a switch block.
A statement in the switch block can be labeled with one or more case or default labels.
It evaluates its expression, then executes all statements that follow the matching case label.
A swich statement is terminated by a break statement.
If the break statement is not used, then all the statements after the matching case label are executed in sequence, regardless
of the expression of subsequent case labels.
So, each break statement is required after each case label besides the final case label or the default label.
The default section handles all values that are not explicitly handled by one of the case sections.
The final break is not required for the final case label or the default label because the flow falls out of the switch
statement.
The use of the break statement is also recommended to easily modify the code and make it less error prone.
Which selection statement should you use? If-else or Switch statement?
The option to use if-then-else statements or a switch statement depends on the readability and
the expression that the statement is testing.
An if-then-else statement can test expressions based on ranges of values or conditions, while a switch statement tests
expressions based only on a single integer, enumerated value, or String object.
The general syntax of the switch statement for the Integer data types (Byte, Short, and Integer data types) is:
// This variable should be declared with any of the Integer data types variable switch (variable){ case 1: statement; break; case 2: statement; break; case 3: statement; break; default: statement; }Case 1
$52$ is not a String variable.
Besides, it is not one of those defined cases.
So, it falls in the default label.
Therefore, the statement in the default label is the output.
Question 2
(2.) The user entered "africa" and expected to see the statement associated with that continent.
However, the user saw another output.
Explain.
africa is not the same as AFRICA based on case-sensitivity.
Hence, the statement in the default label is displayed.
Recall the Piecewise Function program we wrote earlier.
We used Conditional statements to write it.
Let us develop the same program using the Switch statement.
We shall use the Switch statement and the Ternary operator to write the program.
Piecewise Function Application using the Switch Statement and the Ternary Operator
Nested If-Else Statements
We can write more challenging programs using Nested Selection Statements
We can use Nested If-Else statements
One of the syntax for Nested If-Else statement is:
dataType variable; if condition 1{ If condition 2{ statement; } else{ statement; } } else if condition 3{ if condition 4{ statement; } else{ statement; } } else{ statement; }Notice the order in which each nested conditional statement is closed.
Looping statements are:
(1.) For Loop
(2.) While Loop
(3.) Do-While Loop
(4.) For-Each Loop
(1.) The general syntax of a for loop is:
for (initializer; condition; iterator) { statement; }This is also written as:
for (index = beginValue; condition; index compound_assignment someValue) { statement; }(2.) The general syntax of a while loop is:
initializer; while (condition) { statement; iterator; }This is also written as:
index = beginValue; while (condition) { statement; index compound_assignment someValue; }(3.) The general syntax of a do-while loop is:
initializer; do { statement; iterator; } while (condition);This is also written as:
index = beginValue; do { statement; index compound_assignment someValue; } while (condition);(4.) The foreach statement executes a statement or a block of statements for each element in a collection (array)
for(dataType variable : array) { statement; }We shall implement the foreach statement in Module 7 (Arrays).
Branching statements are statements that control the flow of a program by branching or performing jumps
to specific locations.
They include:
(1.) The Break statement
(2.) The Continue statement
Branching statements are not standalone statements.
They are usually embedded in/used with conditional statements and looping statements.
Break Statement
The break statement breaks/stops a loop even when the loop is still running.
In other words, even if the conditions for a loop has not been satisfied, introducing the break statement
at any point in the loop stops the loop and ends the program.
A good advantage of the break statement is that it can be used to end an infinite loop.
Continue Statement
The continue statement causes the program to skip a portion of the loop, and continue
the loop.
In other words, using the continue statement does not run the entire loop. It skips some part of the
loop and then allows the loop to continue.
Let us demonstrate these branching statements.
Please review all the screenshots and all the comments.
Branching Statements: Break Statement, Continue Statement
Let us redo one of the examples we did using Looping statements.
Let us redo the Example (2.) in Looping statements, with Looping and Branching statements.
Redo Example 2 in Iteration Statement using Iteration statement and Jump statement
Let us solve Question (34.) on Arithmetic Sequences
(www.samuelchukwuemeka.com/Sequences/arithmeticSequences.html) using
selection statements, iteration statements, and jump statements.
We shall use iteration statements: for loop, while loop, and do-while loop to solve the question.
Then, we shall use iteration statements, jump statements and selection statements to solve the question.
Application of Statements: Calculate the sum of the $n$ terms of an arithmetic sequence.
Iteration Statements, Selection Statements and Jump Statements
Student: Mr. C, I understand the initialization of the number of terms...as given by the syntax for the loops.
But, why did we initialize the sum to 0?
Teacher: We initialized the sum to 0 because we have to increment each number and add.
$1 + 2 + 3 + 4 + ...$ is the same as saying $0 + 1 + 2 + 3 + 4 + ...$
Student: Why did we initialize?
Why can't we just declare the variable and keep adding the numbers?
Teacher: We have to use "something" to hold the sum.
Because we need to keep adding to "something", we need to initialize "that thing".
"That thing" is the "sum"
Student: The solution on your website used a formula to solve that question.
If we were using formula to solve it, do we need to initialize the sum?
Teacher: Good question.
We do not.
However, some compilers are picky and would insist that you do.
It is a good practice to initialize variables.
Student: Do we always have to intialize to $0$?
Teacher: We do not.
If we were going to multiply (rather than add) numbers...say we declare product as the variable rather than sum, then we have to initialize that variable to $1$ because we shall be multiplying numbers to it rather than adding numbers to it.
The number you use to initialize a variable is to just hold a value to that variable...more like a placeholder.
It does not determine or influence the final result of that variable.
The midterm project is designed to assess your knowledge of Statements in solving real-world problems.
It is a Piecewise Function application.
Any other application will not considered.
Please:
(1.) Visit my website on: Piecewise Functions
(2.) Read the Story to understand the idea of Piecewise functions.
(3.) Read the Overview of Piecewise Functions for more understanding of Piecewise functions.
(4.) Study the Applications of Piecewise Functions
(5.) Review the Project Examples. Ensure you follow all the instructions and directions.
(6.) Review the Midterm Project rubric for your course.
(7.) Complete the Midterm Project for your course.
(8.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(9.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Midterm Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(10.) Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
If you wish to save some time for research:
Please review the Piecewise Function projects done by my previous students.
The direct link of the verifiable websites are included.
(I.) VB Projects
(II.) C# Projects
(III.) C++ Projects
(IV.) Java Projects
You may not do any same application done by any of my previous students for Java
You may do any Piecewise Function application not done by any of my previous students for Java.
If you are not sure what project you may or may not do, please contact me via the school email.
method, function, main method, system pre-defined method, user-defined method, common language runtime (CLR), method signature, method name, method parameter, parameter list, method access, access level, public, private, abstract, sealed, return value, return type, void, method invocation, instance method, static method, argument, argument list, pass parameters by value, parameter arrays, modifier, local variables, return keyword, value parameters,
Students will:
(1.) Discuss methods.
(2.) Pass parameters to methods.
(3.) Overload methods.
(4.) Write programs that solves real-world problems using methods.
(1.) Textbook Chapter
(2.) Java Methods
(www.w3schools.com/java/java_methods.asp)
Begin from Java Methods to Java Recursion
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type Java Methods or Java Functions in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type Java Methods or Java Functions in the search bar and view/read the results.
(1.) Textbook Chapter
(2.) Java Methods
(www.w3schools.com/java/java_methods.asp)
Begin from Java Methods to Java Recursion
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type Java Methods or Java Functions in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type Java Methods or Java Functions in the search bar and view/read the results.
Teacher: Guess what?
Student: We have been using a method since we wrote our first Java program.
What is that method called?
Student: You mean the main method?
The static void main(String[] args)
Teacher: That is correct.
As we mentioned in the first module, every Java program is written in the main
method.
The static void main(string[] args) method is the system pre-defined main method
The methods we shall discuss in this module are user-defined methods
The main method is the entry point for every Java application, and it is called by the
common language runtime (CLR) when the program is started.
It is the only method that is called automatically regardless of the order in which it is
written.
In other words, it does not matter if we write the main method before or after the
user-defined method
The main method is called first by the Java program.
This implies that any other user-defined method should be called in the main method
directly or indirectly.
Note that we cannot use the reserved word, main as the name of any method we define
(user-defined method).
A method is a block of code that contains a series of statements.
It is also known as a function.
It allows for the reusability of those statements/codes, and perform some action when called.
Reusability of codes: define one time, use many times.
Anytime the method is called, the statements in that method are executed.
Method Signature is the set of attributes used to declare a method.
They consist of the:
(1.) Access level: such as public or private.
By default, the access level is private.
The access level is optional.
(2.) Modifier: such as abstract or sealed.
The modifier is optional.
(3.) Return value or void
Every method must have either a return value or a void.
If the method has void, then it has no return value.
(4.) Method name: the name of the method.
It is important to use an appropriate identifier.
Method names (identifiers) in Java begin with an uppercase letter (preferably Pascal casing)
This is required.
(5.) Method parameters: Method parameters are enclosed in parentheses.
If the method has no parameter, then the parenthesis is empty.
This implies that a parenthesis is required.
If the method has parameters, the parameters are separated by commas.
We shall discuss some of the method signatures in this module.
We shall discuss the rest in the Advanced Java course.
Usually, a method takes in parameters.
Parameters are normally variables, and we declare them as we declare variables.
They are local variables to the method that takes them.
Student: To be honest, I have no idea what you just said.
What are parameters? arguments?
Teacher: Let us review this example.
Assume we have this program with a user-defined method:
// Method package methods; public class Program { // Declare the method: SumNumbers // Parameters are: num1 and num2 public static int SumNumbers(int num1, int num2) { return num1 + num2; } public static void main(String[] args) { // Call the method // Arguments are 5 and 7 SumNumbers(5, 7); // Print what you called System.out.println(SumNumbers(5, 7)); } }In user-defined method:
int result = SumNumbers(5, 7);
System.out.println(result);
accessLevel static void MethodName(parameterList)
{
statements;
Console.WriteLine($"something");
}
accessLevel static dataType MethodName(parameterList)
{
statements;
return something;
}
Celsius Temperature to Fahrenheit Temperature Conversion
Given: The Human Body Temperature in Celsius Temperature ($37^\circ$)
To Calculate: The Fahrenheit Temperature
Formulas:
$
fahrenheitTemp = \dfrac{9 * celsiusTemp}{5} + 32 \\[5ex]
$
Fahrenheit Temperature to Celsius Temperature Conversion
Given: The Human Body Temperature in Fahrenheit Temperature ($98.6^\circ$)
To Calculate: The Celsius Temperature
$
celsiusTemp = \dfrac{5 * (fahrenheitTemp - 32)}{9} \\[5ex]
$
Teacher: Did you notice the difference?
Student: Yes...I think so
I prefer the Void type method
We can easily use the variable names rather than writing the value. I mean ...
I would prefer to use the variable: fahrenheitTemp rather than 98.6
Teacher: I prefer the void method too
It helps if we want to return multiple values along with a message in a System.print() method
Let us write a code example that uses an Input/Output feature.
We shall also demonstrate the use of local variables.
Formulas:
$
fahrenheitTemp = \dfrac{9 * celsiusTemp}{5} + 32 \\[5ex]
celsiusTemp = \dfrac{5 * (fahrenheitTemp - 32)}{9} \\[5ex]
$
Discriminant of a Quadratic Trinomial (no worries, we do not discriminate in Mathematics 😊)
Calculate the Discriminant of a Quadratic Trinomial in General Form
(1.) Program Requirement
Every line of executable code in any Java application must be inside some method.
(2.) Reusability: write one time, use several times
Methods are useful for performing repeated or shared tasks such as frequently used calculations, text and control
manipulations, and database operations.
We can just define a method one time, and then reuse the statements inside the method as many times as we want
whenever we call that method.
(3.) Easier Code Readability and Faster Debugging
Imagine a "big" program (program with long lines of codes).
Methods allow such programs to be broken into discrete logical units.
This helps for easier code readability and faster debugging.
(4.) Avoiding Code Duplication
After developing a method in one program, it can be reused in another program with little or no modifcation.
Generally, there are two ways of passing parameters: By Value and By Reference.
However, in Java; parameters are passed only by value.
In the previous examples we did, we passed the parameters by value.
In passing a parameter by value:
(1.) Protection: Exposure of calling variables to change
The advantage of passing a parameter by value is that it protects a variable from being changed by the method.
(2.) If the calling code element underlying the argument is a nonmodifiable element, declare the corresponding parameter
by value.
No code can change the value of a nonmodifiable element.
If you would like to know how to pass parameters by reference, please review the notes in my VB.NET and C# courses.
For all applicable questions, please:
(A.) Use the Void type and/or the Data type as your method
(B.) Use appropriate method names in line with Java naming conventions.
(C.) Include an appropriate message with your result.
(D.) Use an Input/Output feature if you wish.
(1.) Using Data Type Method Example: Input/Output Feature, include a condition that asks the user if the
quadratic trinomial is in general form.
If the user says No, ask the user to arrange the quadratic trinomial in general form before proceeding.
Then, quit the program.
If the user says Yes, proceed to run the program.
Test both conditions.
Arithmetic: Questions (2.) through (5.)
Please review the Definitions of Numbers on Numbers website:
Numbers and Notations
(https://numbersandnotations.appspot.com/#definitions)
Please make sure you indicate the type of number in your comments.
(2.) Write a method that prints any of those types of numbers between one and thirty ($1$ and $30$ are included)
(3.) Write a method that prints the first thirty numbers of any of those types of numbers.
Focus on the first positive thirty numbers of those kind of numbers.
(4.) Write a method that asks the user to input two values (those values could be
positive, zero or negative)
The method should print all the numbers for any of those types of numbers between those two
values.
Those two values should be included if they are part of those type of numbers.
(5.) Write a method that asks the user to put in a value (that value could be positive, zero,
or negative)
The method should print thirty values of those types of numbers up to and including the
user-input value.
Geometry: Questions (6.) and (7.)
Please review the Mensuration Formulas on Mensuration website:
Mensuration
(https://www.samuelchukwuemeka.com/Mensuration/mensuration.html)
Please make sure you indicate the type of figure/shape in your comments.
(6.) Write a method that asks the user to input the required parameters for any
two-dimensional figure.
The method should return the area and perimeter of that figure.
(7.) Write a method that asks the user to input the required parameters for any three-dimensional figure.
The method should return the surface area and volume of that figure.
Strings/Quotes: Questions (8.) and (9.)
Find a quote from any of your favorite authors or your favorite quote.
If you do not have any favorite author or a favorite quote, make up a quote yourself, and
indicate that it is your own quote.
(8.) Write a method that prints all the vowels in that quote, and returns the count.
(9.) Write a method that prints all the consonants in that quote, and returns the count.
(10.) Arithmetic:
Question (4.) on Page 165 of your textbook.
(11.) Acturial Science:
Question (9.) on Page 165 of your textbook.
(12.) Algebra:
Question (5.) on Page 165 of your textbook.
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java Methods: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/method/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(13.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for Java
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for java programmer, you might be surprised that even for entry level positions
for a Java Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with Java.
However, if you find out that C# would be better in solving a particular problem in your workplace,
then you need to use C# unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in Java and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in Java and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
C# Function: Exercises, Practice, Solution
(https://www.w3resource.com/csharp-exercises/function/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(14.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program. Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different statement to work on the same method used by your colleague.
For example: if your colleague used an iteration statement in a function, you may use a conditional statement or a
jump statement or a different iteration statement to write the same method to give the same output.
(2.) Review the post (Discuss Questions) done by your colleagues.
Use a different method to display the same output of the program done by your colleague.
For example: if your colleague used the Data type method, use the Void type method to write the program to
display the same output.
You may include an appropriate message along with the output.
(3.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(4.) Other substantive responses.
Algebra: Questions (1.) and (2.)
Please review the Roots of a Quadratic Equation on the Expressions and Equations website:
Quadratic Equations
(www.expressions-equations.appspot.com/#quadraticEquations)
There is a calculator I developed that calculates the roots of a quadratic equation and displays a message.
(I.) Write a method that requests the user to input the three values: (as seen on my calculator), and
display the same message that is displayed by my calculator.
In other words, the output and message from your calculator should be the same as the output and
message from my calculator when the user inputs those three values.
Test your program for each of the four cases of the discriminant regarding the nature of the roots
of a quadratic equation as seen in Numbers (1a.), (1b.), (2.) and (3.) on my website.
(II.) Submit clear screenshots of your program.
(III.) Submit clear screenshots of the output of your program for the four cases.
(IV.) Submit clear screenshots of the output of my calculator for the four cases.
(III.) and (IV.) should display the same messages.
(1.) Console Application
(2.) Desktop Application
(3.) Geometry:
Question (8.) on Page 164 of your textbook.
(4.)
array, list, ArrayList, single-dimensional array, one-dimensional array, dimension, rank, data structure, array type, array elements, square brackets, index, array index, array length, sort array, arrays as parameters, arrays as arguments, array methods, new keyword, Object keyword, tuple, ListBox, MultiLine TextBox, parallel arrays,
Students will:
(1.) Discuss arrays.
(2.) Implement array methods.
(3.) Pass arrays as function parameters.
(4.) Pass arrays as arguments.
(5.) Write programs that use arrays to solve real-world problems.
(1.) Textbook Chapter
(2.) Arrays: Part 1 by Oracle
(https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html)
(3.) Arrays: Part 2 by Oracle
(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
(4.) Arrays Class by Oracle
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(5.) Type Java Array and/or Java Tuple in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(6.) Type Java Array and/or Java Tuple in the search bar and view/read the results.
(7.) Tuple Class by Oracle
(https://docs.oracle.com/middleware/11119/jdev/api-reference-esdk/oracle/javatools/util/Tuple.html)
(8.) Tuple Interface by Oracle
(https://docs.oracle.com/javaee/7/api/javax/persistence/Tuple.html)
An Array is a list or data container that contains:
(1.) single or multiple values of the same data type or
(2.) multiple values of different data types
The values stored by an array are known as the elements or the members of the array.
The dimension of an array is the direction in which one can specify the elements of the array.
Example:
Record the ages of the students in Mr C's class.
We have only one variable: age.
This is a one-dimensional array...array of integers
A one-dimensional array is also known as a single-dimensional array.
Each student in Mr. C's class takes at least one course this semester.
Record the number of courses taken by each student in Mr. C's class.
Some of the courses are one-credit, two-credit, three-credit, four-credit courses.
Assume the tuition for each course depends on the number of credit units.
Calculate the total cost of all the courses taken by all the students in Mr. C's class.
For us to do this, we need to list the number of courses taken by each student in Mr. C's class. We can represent this in
the column.
We also need to calculate the cost of the courses taken by each student. We can represent this in the row.
So, we have two variables: courses and cost.
This is a two-dimensional array.
The column is the array of integers ... the number of courses.
The row is the array of doubles ... the cost of the number of courses taken by each student.
We can then find the total cost...connect this explanation with Matrices in Algebra
In this module, we are only concerned with one-dimensional array.
The rank of an array is the number of dimensions in the array.
This implies that the rank of a one-dimensional array is 1
The rank of a two-dimensional array is 2
The rank of a three-dimensioanl array is 3 and so on and so forth.
Why Are We Learning Arrays?
Assume you want to work with five different integers; rather than declare five different
variables for the five integers, it is much better to declare a single integer array that will contain all five
integers.
When we declare an array in Java:
(1.) We must declare the data type of the array.
(2.) We may or may not not indicate the size of the array.
Notable Notes About Arrays
(1.) An array is declared by specifying the data type of its elements.
You may or may not write the elements when you declare the array.
If the elements are of the same data type, then the array is declared by specifying that data type.
If the elements are of different data types, the the array is declared by specifying object as the data type.
When the elements are specified, they are enclosed in curly brackets or braces.
(2.) If the elements are of the same data type or of different data types, the var keyword can also be used.
The new keyword is used to specify the elements of an array if the array was declared without the elements.
Let us review several ways of declaring arrays.
/* elements are not specified elements are the same data type */ dataType[] arrayName; /* elements are not specified elements are the same data type array size is specified */ dataType[] arrayName = new dataType[arraySize]; /* elements are specified, separated by comma elements are the same data type */ dataType[] arrayName = {array elements}; /* elements are specified, separated by comma elements are the same data type array size is specified */ dataType[] arrayName = new dataType[arraySize] {array elements}; /* elements are not specified elements are of different data types */ object[] arrayName; /* elements are not specified elements are of different data types array size is specified */ object[] arrayName = new object[arraySize]; /* elements are specified, separated by comma elements are of different data types */ Object[] arrayName = {array elements}; /* elements are specified, separated by comma elements are of different data types array size is specified */ Object[] arrayName = new object[arraySize] {array elements};(3.) When an array is created, the number of dimensions and the length of each dimension are established.
array[index] = element;
ForEach Loop | For Loop, While Loop, Do-While Loop |
---|---|
(1.) Loops through each array element without using a counter. | (1.) Loops through each array element using a counter. |
(2.) The length of the array is not needed. | (2.) The length of the array is needed. |
Student: What if we want to keep adding elements to the array?
Teacher: Very good question.
In that case, we need to use an ArrayList
We shall cover ArrayList in details in the Advanced Java course.
However, let us review an example.
Example 2: Demonstrate the implementation of an ArrayList
Student: Mr. C
Why did you change the for-each loop?
That was not the way you used it in the first example.
I do not like the one you just used.
Teacher That is fine.
The approach I used is a functional operation for the for-each loop
But you may use the for-each loop that we used for the perfect squares.
This is what I did.
Initially, I used the for-each loop that we used in Example 1.
Then, I saw the light bulb warning by the side on the line.
I clicked it and clicked the option to use functional operation.
I do not like to see warnings in my code.
Hence, I used it.
Let us review more examples.
Example 3: Create an array of strings of size 4
Print the array.
Print the fourth element of the array
Sort the array
Print the sorted array.
Print the fourth element of the sorted array.
Student: Mr. C
Just to be sure...
Because sometimes you declare several variables
And sometimes you use only variable
It can be confusing at times
So, the same variable that you used in the array and the sorted array: name
You used it because it was declared inside the loop?
So, it is only known within the loop? It is not known outside the loop...is that right?
Teacher: That is correct
Student: So, if I try to use that variable outside the loop, the program will not recognize it?
Teacher: That is correct
Student: But why did you not declare several variables like you did in the previous example?
Teacher: It is just a choice
You can declare several variables if you wish.
Let us do an input-output feature.
Let us also demonstrate the use of an array that stores values of different data types.
Example 4: Input-Output Feature for a Pizza Restaurant
Statistics comprises Data Analysis.
Data Analysis is part of Data Science.
Data Science is part of Computer Science/Programming.
As a programmer, it is very likely that you will deal with data.
In this course, we shall focus only on some of the Descriptive Statistics of Data Analysis.
The Descriptive Statistics that we shall discuss in this course are:
(1.) Measures of Center:
Also known as the Measures of Central Tendency
They are the: Mean, Median, Mode, and Midrange.
(2.) Measures of Spread:
Also known as the Measures of Dispersion or the Measures of Variability or the Measures of Variation
For this course, we shall focus on the: Range, Variance, and Standard Deviation.
(3.) Measures of Position:
Also known as the Measures of Location
For this course, we shall focus on the: Five Number Summary of Data
They are the: Minimum, First Quartile, Second Quartile, Third Quartile, and Maximum.
The First Quartile is also known as the Lower Quartile or the 25th Percentile
The Second Quartile is also known as the Median or the Middle Quartile or 50th Percentile
The Third Quartile is also known as the Upper Quartile or 75th Percentile
Some Java packages have predefined methods used for calculating some of these measures.
We shall calculate the rest of the measures.
Let us write program examples of descriptive statistics using Java
The formulas used are the formulas on the Descriptive Statistics website
(1.) Formulas for the Measures of Center
(2.) Formulas for the Measures of Variation
(3.) Formulas for the Measures of Location
Example 5: Data Analysis: Descriptive Statistics of Raw Ungrouped Data with Java
Let us do an example that uses an Input-Output Feature
Ask the user how many numeric values that he/she would like to enter.
Store the values in an array.
In this case, it is better to write a method.
Write that a method that computes the descriptive statistics of the array.
Textbook Questions
(1.) Question (1.) on Page 409
(2.) Question (2.) on Page 409
(3.) Question (3.) on Page 409
For Questions (4.) and (5.)
Please review these Sorting Techniques and Algorithms
(https://www.samdomforpeace.com/DataStructures/Sorting.html)
(4.) Write a method (user-defined method) that sorts an array in ascending order using any of the techniques.
Use an array size of at least 3 (array size $\ge 3$).
Specify the technique.
(5.) Write a method (user-defined method) that sorts an array in descending order using any of the techniques.
Use an array size of at least 3 (array size $\ge 3$).
Specify the technique.
(6.) Write a method (user-defined or system-defined method) that divides an even-sized unsorted array into two equal halves, sorts the
first half in ascending order, and sorts the second half in descending order.
Use any even size of at least 8 (array size $\ge 8$).
(7.) Write a method (user-defined or system-defined method) that divides an even-sized unsorted array into two equal halves, sorts the
first half in descending order, and sorts the second half in ascending order.
Use any even size of at least 8 (array size $\ge 8$).
For Question (8.)
Please review the: Arrays Class by Oracle
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html)
Scroll down till you see All Methods
(8.) Implement any two methods.
(9.) Please review the Solved Examples on the Measures of Center
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of center for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(10.) Please review the Solved Examples on the Measures of Spread
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of dispersion for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(11.) Please review the Solved Examples on the Measures of Position
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of location for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(12.) Please review the Solved Examples on Descriptive Statistics
Find any question that has a dataset that can be entered into an array.
(a.) Write a program that computes the measures of center and/or the measures of variability and/or the measures of position for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java Array: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(13.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
For those who do not mind messing around with several languages at the same time
Student: Excuse me, Mr. C
This course is only for Java
What do you mean?
Teacher: You are correct.
But, these subsequent questions are not for everyone.
That is the reason I am putting them at the end.
I have a question for you.
Have you ever seen any IT/Computer Science position that requires the knowledge of only one programming language?
Student: I have not checked, Sir.
Teacher: If you intend to be in the IT/Programming field for the long run, at least four (four or more)
languages are required.
If you look for IT positions at Indeed.com or other career/job websites, you will realize what I mean.
Search for java programmer, you might be surprised that even for entry level positions
for a Java Programmer; they require you to have a working knowledge of several other programming languages.
Mr. C is preparing you for that...if you intend to work in the programming field for a long time.
Besides, this is a critical thinking approach.
I am required to develop and promote critical thinking questions for my students.
A programmer is basically a problem-solver irrespective of the programming language used to solve the problem.
Yes, we are working with Java.
However, if you find out that C# would be better in solving a particular problem in your workplace,
then you need to use C# unless your employer says otherwise.
The knowledge of several languages is a good asset. It makes you highly valuable.
Further, anyone who attempts any of the subsequent questions will still have to write the program in Java and get the same
result.
The questions and solutions are in another language.
But the student will have to write the program in Java and come up with the same solution. So, we are still on track.
It is critical thinking...multiple approaches to solving a question.
Be it as it may, these subsequent questions are not required.
It is okay even if you do not look at them. 😊
C# Programming Exercises, Practice, Solution by W3Resource
Please review:
C# Array: Exercises, Practice, Solution
(https://www.w3resource.com/csharp-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(14.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
C++ Programming Exercises, Practice, Solution by W3Resource
Please review:
C++ Array: Exercises, Practice, Solution
(https://www.w3resource.com/cpp-exercises/array/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(15.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program.
Please make sure your program output is the same solution
JavaScript Programming Exercises, Practice, Solution by W3Resource
Please review:
JavaScript Array: Exercises, Practice, Solution
(https://www.w3resource.com/javascript-exercises/javascript-array-exercises.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(16.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program. Please make sure your program output is the same solution
JavaScript Programming Exercises, Practice, Solution by W3Resource
Please review:
JavaScript Searching and Sorting Algorithm: Exercises, Practice, Solution
(https://www.w3resource.com/javascript-exercises/searching-and-sorting-algorithm/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(17.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write the program in Java
Run the program. Please make sure your program output is the same solution
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different statement to work on the same Array or the same Tuple used by your colleague.
For example: if your colleague used an iteration statement in an array, you may use a conditional statement or a
jump statement or a different iteration statement to write the same Array or the same Tuple to give the
same output.
(2.) Review the post (Discuss Questions) done by your colleagues.
Use a different data structure to display the same output of the program done by your colleague.
For example: if your colleague used an Array, use a Tuple to write the program to display the same output.
(3.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(4.) Review the post (Discuss Questions) done by your colleagues.
Use a different user-defined array method and/or system-defined array class method to work on the same program
done by your colleague.
(5.) Other substantive responses.
Textbook Questions
(1.) Question (4.) on Page 409
(2.) Question (5.) on Pages 409 and 410
(3.) Please review Example 4: Input-Output Feature for a Pizza Restaurant
Please do these tasks.
(a.) Modify the application to include the name and slogan of the restaurant in the customer's receipt.
In other words, Lines #16 - 19 should be included in the customer's receipt on the condition that those lines should be written
only one time in the project but called twice. Do you understand what I mean? We did that concept in Module 6
Submit the screenshots for the code and the output.
(b.) Samuel entered an order for a customer.
He noticed that the total cost for that customer was less than similar orders he gave past customers.
So, he reviewed his entries and noticed that he mistakenly entered "Extra cheese" rather than "extra cheese".
He did not realize that the application was data entry case-sensitive.
He met with his manager and asked her to reconsider the application.
The manager contacted you, the programmer; and informed you about the concern.
Using at least five different sentences, address this issue.
Consider the fact that the manager is not a programmer.
Inform the manager of several options/applications and suggest the best option.
Asking the manager to ensure that all her employees are properly trained on case-sensitive data entry is not considered
an option in this case.
Write your responses on the Blackboard Editor.
Cite your source(s) as applicable.
For Questions (4.) through (7.):
Please review the GUI Programming Examples.
(I.) User-defined methods are required.
(II.) Parallel arrays are required. One array should be for the data variable and the other array should be for the
frequency.
(III.) You may use a pre-defined array (ListBox) or you may allow the user to enter the values (MultiLine TextBox)
(IV.) Desktop application is optional. You may develop a console application.
(V.) Multiple forms are optional.
(4.) Please review the Solved Examples on the Measures of Center
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of center for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(5.) Please review the Solved Examples on the Measures of Spread
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of dispersion for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(6.) Please review the Solved Examples on the Measures of Position
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of location for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
(7.) Please review the Solved Examples on Descriptive Statistics
Find any question that has Ungrouped Data with frequency.
(a.) Write a program that computes the measures of center and/or the measures of variability and/or the measures of position for that question.
Test the program output with the results on the
Descriptive Statistics Calculators
(b.) Solve the question.
Check your answer with the solution on the website.
Students will:
(1.)
(2.)
(1.) Textbook Chapter
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type Java Multidimensional Array and/or Java Jagged Array in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type Java Multidimensional Array and/or Java Jagged Array in the search bar and view/read the results.
(1.)
(1.)
There are three options for your Final Exam
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Please click the Gradebook and complete all the assessments there.
The assessments that are automatically graded count for the Final Exam.
The assessments that are to be manually graded count for the Final Project.
Access the MindTap Course
Course Key: MTPPC12Q2KTJ
This exam is designed to assess your understanding of the beginning Java concepts.
You have reviewed several topics and several concepts in each topic for eight modules.
Pick at least $1$ concept in at least $1$ topic in each of the $8$ modules.
That gives at least $8$ concepts in $8$ different topics in $8$ modules.
Find two more concepts in any topic in any module.
That gives $10$ concepts.
For each concept, please:
(1.) Write at least three sentences about that concept.
(2.) Develop a program about that concept.
In other words, write at least one code example about the concept.
Run the code.
Display the output.
Submit clear screenshots of your program (code and output)
Deliverables:
(1.) 10 concepts in 10 different topics for 8 modules
Please write the: Module number, the Topic, and the Concept
(2.) Three sentences for each concept.
(3.) Code for each concept.
(4.) Output for each concept.
Please submit all these information as a zipped folder (.zip only) in the Final Exam folder of the Blackboard course.
Candidates for this exam are application developers working with Java 6 SE or later, secondary and immediate
post-secondary level students of software development, or entry-level software developers.
Candidates should have at least 150 hours or instruction or hands-on experience with Java, are familiar with its
features and capabilities, and understand how to write, debug and maintain well-formed, well documented Java code.
Please review some of the questions and answers of the
Microsoft Introduction to Programming Using Java Exam
(https://www.itexams.com/exam/98-388)
This is Free But Requires Patience
Focus on what we covered (Beginning Java).
However, you are welcome to review all of them and attempt the Advanced Java topics.
Student: Mr. C, you are giving us a final exam with the answers?
How nice of you?
Teacher: Yes of course, I am nice. 😊
But, please read on.
Please:
(1.) Review Past Questions and Answers
You may not do any of those questions because they have been done already.
(2.) Do not attempt any question already indicated by your colleague.
If your colleague indicates by writing that he/she is working on a question, then you need to find another question.
No two or more students are permitted to do the same question.
(3.) Pick any five questions.
(4.) Go to the Final Exam Questions forum of the Blackboard course.
(5.) Write the question numbers in that forum only if it has not been written by any other student.
In other words, you need to review any questions posted by your colleagues and make sure that you do not attempt
the same question.
(6.) Explain the solutions of those five questions using your own explanations
and your code examples.
(7.) Number the questions, the solutions, your code examples and output, and your
explanations based on the actual question numbers.
(8.) Submit the actual questions, the corresponding numbered solutions, your
corresponding numbered explanations and your corresponding code examples and output and any other relevant
information in the Final Exam folder of the Blackboard course.
(9.) Make your work easy for me to grade.
In other words, write detailed clear specific explanations.
Do not give me any avenue to deduct points.
This exam is designed to assess your understanding of the Java language.
Please review all the questions and answers of the
Advanced Placement (AP) Computer Science Exams
Student: Mr. C, you are giving us a final exam with the answers?
How nice of you?
Teacher: Yes of course, I am nice. 😊
But, please read on.
Please:
(1.) Review Past Questions and Answers
You may not do any of those questions because they have been done already.
(2.) Do not attempt any question already indicated by your colleague.
If your colleague indicates by writing that he/she is working on a question, then you need to find another question.
No two or more students are permitted to do the same question.
(3.) Pick any five questions.
(4.) Go to the Final Exam Questions forum of the Blackboard course.
(5.) Write the question numbers in that forum only if it has not been written by any other student.
In other words, you need to review any questions posted by your colleagues and make sure that you do not attempt
the same question.
(6.) Explain the solutions of those five questions using your own explanations
and your code examples.
(7.) Number the questions, the solutions, your code examples and output, and your
explanations based on the actual question numbers.
(8.) Submit the actual questions, the corresponding numbered solutions, your
corresponding numbered explanations and your corresponding code examples and output and any other relevant
information in the Final Exam folder of the Blackboard course.
(9.) Make your work easy for me to grade.
In other words, write detailed clear specific explanations.
Do not give me any avenue to deduct points.
For example:
First Task: Notify your colleagues of the questions you intend to do.
In the Final Exam Questions forum of the Blackboard course: you may write:
Hey guys, I am doing $2006$ Question ($2$.), $2010$ Question ($3$.), ... etc.
Second Task: Do the questions.
(1.) $2006$ Question (2.)
Write the question or take screenshots of the question.
Develop the Java program. Write detailed comments.
Run the program.
Submit clear screenshots of the code and results.
(2.) $2010$ Question (3.)
Write the question or take screenshots of the question.
Develop the Java program. Write detailed comments.
Run the program.
Submit clear screenshots of the code and results.
Third Task: Submit all deliverables.
Submit clear screenshots of the: actual questions, the Java program (including comments) of the solutions,
and the results of the five questions in the Final Exam folder of the Blackboard course.
Should you have any questions, please let me know.
Thank you.
There are three options for your Final Project.
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Please click the Gradebook and complete all the assessments there.
The assessments that are automatically graded count for the Final Exam.
The assessments that are to be manually graded count for the Final Project.
Access the MindTap Course
Course Key: MTPPC12Q2KTJ
It is important you communicate with me for approval prior to doing this project.
Because the course deals with only desktop applications and console applications,
(rather than web applications and mobile applications), you may not do any project that requires a web server
such as contact forms and registration forms among others.
The final project is designed to assess problem-solving skills using the knowledge you have acquired in the
course.
In that regard, solving at least a real-world problem using the knowledge gained in the course is expected.
(1.) Think about any of these companies: our Institution: Kent State University; your local campus; your work place; public and
private schools (excluding home schools); organizations, firms, and businesses
(excluding controversial firms and the like).
Any company you choose should have a verifiable website.
The direct link of the company's website is required.
(2.) Identify a problem on the website that you want to solve.
The problem must be solved by programming using the knowledge acquired from any of the course
topics/concepts/description/learning objectives.
Think about your Midterm Project. You solved a problem: calculating bills, federal taxes, etc.
(3.) Develop the computer program to solve the problem.
Test the program to ensure that it works.
Write detailed comments as applicable.
(4.) Prepare a Documentation Manual/Reflection for the project.
Please cite your sources accordingly.
What is the company?
What is their website?
What problem did you identify?
Did you solve the entire problem or part of the problem?
What course topics/concepts/description/learning objectives did you apply in solving the problem?
How did you solve the problem?
Did you encounter any issues while trying to solve the problem?
Are there any limitations to the project?
Are there any recommendations to the company?
Deliverables:
(1.) Program (all files)
(2.) Clear screenshots of your program (code and output)
(3.) Project Reflection/Documentation Manual
Please submit all these information as a zipped folder (.zip only) in the Final Project folder of the Blackboard course.
The final project is designed to assess your understanding and analysis of data using the knowledge you have
acquired in the course.
Please:
(1.) Visit my website on: Descriptive Statistics
(2.) Review the information for a good understanding of Descriptive Statistics.
It is highly likely that you have a prior knowledge of this topic. Is that right?
(3.) Click the Project link.
(4.) Review the Project Examples. Ensure you follow all the instructions and directions.
(5.) Complete the Final Project for your course.
(6.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(7.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Final Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(8.) Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
Course using Java abstract data types and objects, object-oriented, event-driven design, file organization and access, and systems programming concepts. Prerequisite: IT 20011.
By the end of this course, you should be able to do the following:
(1.) Demonstrate Advanced Inheritance Concepts including Abstract Classes, Dynamic Method Binding Arrays of
Subclass Objects, Software Design and Interfaces.
(2.) Perform Exception Handling and Debugging.
(3.) Demonstrate the use of File Input and Output.
(4.) Explain the role of Multithreading.
Students will:
(1.) Discuss the terms used in object-oriented programming.
(2.) Create a class.
(3.) Create a constructor.
(4.) Implement different constructors.
(5.) Overload constructors.
(6.) Create a destructor (destroy a constructor).
object-oriented programming, class, object, namespace, access modifier, public, private,
(1.) Textbook Chapter
(2.) Java Classes: From Java OOP to Java Modifiers by W3Schools
(3.) Object-Oriented Programming Concepts by Oracle
(4.) Designing a Swing GUI in NetBeans IDE
by Apache NetBeans
(5.) Learning Swing with the NetBeans IDE
by Apache NetBeans
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type Object-oriented Programming in Java or OOP in Java in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type Object-oriented Programming in Java or OOP in Java in the search bar and view/read the results.
If you are using the NetBeans IDE:
Please:
(1.) Review the screenshots of Module 1 to increase the font size of: your code in the IDE and
the output of your program in the IDE.
Teacher: So, we discussed data types and variables
We did some work/calculations with the data types and variables.
Our project started to grow.
We needed to lessen codes and reuse codes. Simply put, we wanted to do more with less.
We introduced functions to achieve that goal.
Functions included the data types, variables and the work/calculations done with
them.
The project started getting large and popular. It needed to serve more clients.
What should we do?
Can we join data types, variables and functions as a package? Can we reuse that package as
much as we want?
The answer is Yes!
Welcome to Classes
Student: Where did the object-oriented come from?
Teacher: Good question.
Remember how we call a function any time we want to use that function?
We shall 'call the class', well create a new instance of the class anytime we want to use that class.
So, whenever we create an instance of the class because we want to use that class, we have created an
object
That means that an object is an instance of the class.
Student: So, what you are saying is that an object is simply calling the class in order to use it?
Just like we do in functions?
Teacher: That is correct.
Simply put, creating an object means calling the class.
We can create as many objects as we want by calling a class anytime we want.
The class is a package of data types, variables and functions.
Actually, a class is a package of fields, methods, and properties.
Creating and using objects to develop computer programs is known as object-oriented programming.
Encapsulation is the combination of fields, properties, methods, and events of an object in a class(capsule).
In other words, keep all the data and program logic in one place.
Student: You introduced some words.
Teacher: Yes, I did.
No worries you will get used to them.
The field is the data type and variable.
The field is often referred to as an attribute.
The method is a function
The property allows us to change the fields.
The fields, properties, and methods are referred to as the class members
Recall how we write out first application in Module 1 of the Beginning Java class
As seen from the screenshots, a public main class is created anytime a Java project is created.
The name of the public main class is the same as the name of the Java file.
Class names are written in uppercase or Pascal case.
What is my first greeting to my students?
Welcome to our IT 36311: Advanced Java Programming class!
So, let us create a class called ComputerScience
Example 1: Welcome to our IT 36311: Advanced Java Programming class!
Notice we used the keyword, new
And we greeted the student object, student1 with the greeting we defined in the ComputerScience
class by joining the object with the variable using the member access expression, . (the
period punctuation mark).
Student: This is what I don't get.
Why use public?
Teacher: We used public so we could access that variable, greeting outside the
class that it was defined.
If we used private, we would not be able to access the variable outside that class.
No worries, we shall discuss that later in this module.
Example 2: Let us greet two students.
In this case, we have to create two objects.
The teacher should greet the student.
Create a class that has three members: three fields and one method.
Student: Mr. C, you used the same name for the field and for the main method
Is that not a bad programming practice?
Teacher: My dear, you are correct.
It is better to use different names.
Please correct it on your end.
Teacher: What happens as our project expands?
If we want more functionalities (fields and methods), do we have to keep writing them in the same program?
Can we write this using another approach?
Student: I think so...since you talked about it.
Teacher: Sure...we can.
Let us create another Java file.
We shall leave the initial class in the Java file...the file where it is.
Let us create another Java file and put the main method in it.
Both files should be in the same project folder.
This means that both files will have the same package.
The second file that we will create will be a new Java class named Greeting
Because this file will have the main method, we shall use it as the main class.
Student: I guess this is similar to what we did in C++...with header files.
where we create a header file, write our programs, then include it (by referencing it) in another file that
has the main method.
Teacher: That is correct.
Let's do what we just discussed.
Cut the entire main method in the ComputerScience class and Paste it in the Greeting class
Go ahead and run it.
Wait. Before we run it, let us give another name for the String, "greeting". Let's call it "welcome".
Also, modify the comments in both classes.
As you can see, we have the same output.
This is known as using Multiple Classes
It is necessary for better organization of classes.
We can have as many classes as we want, provided all those classes are under one package.
Student: What if students want to greet their fellow students?
Teacher: Good question.
We want students to greet themselves.
We already know that Chukwuemeka is the teacher and Samuel is the student.
Let's say we want another student, Dominic.
The teacher would greet the two students, Samuel and Dominic.
Each student will greet the other as well.
In other words:
Chukwuemeka will greet Samuel
Chukwuemeka will greet Dominic
Samuel will greet Dominic
Dominic will greet Samuel
So, we have four greetings of "Welcome to our Class!"
Static Methods
If we do not want to create an object and use the object to call the method, we can just use a static method
In that case, the keyword, static is used with the name of the method.
The use of a static method also allows us to call the method directly
Let us review an example.
Student: There's much limitation with the static method.
We might as well just write the statements directly under the class.
I have a question.
What if we have different names for the teachers and students?
Do we need to keep defining each name as a field when we have a new teacher and new students?
Teacher: Good question.
More functionalities means that we should find a way of achieving the same output with less code.
This leads to...
What we can do to address your question is to create a constructor.
A constructor in Java is a special method that:
has the same name as the class; used to initialize objects; and
does not return values.
Hence, whenever we create an object (the instance of the class), the constructor is called.
The constructor is a method. So, it needs to have an access modifier.
Note that it should have the same name as the class name.
So, you can say that is a special method because it has an access modifier, has the same name as the
class name, may or may not have parameters that would be defined as initial variables or values of the class
members, and does not return any value.
There is always at least one constructor in every class.
If a class is created without a constructor, the compiler creates a default constructor for that class.
Java constructors are:
(1.) Default Constructor (also known as a Parameterless Constructor or No-argument Constructor)
(2.) Parametized Constructor
A default constructor is a constructor that has no parameter.
It is a parameterless constructor.
The syntax for a default constructor is:
access modifier ClassName() { statement; }Let us implement a default constructor
A parametized constructor is a constructor that has at least one parameter.
The syntax for a parametized constructor is:
access modifier ClassName(parameter1, parameter2, ...) { statement; }We shall use parametized constructors frequently in the course.
We can overload constructors, just as we overload methods
This implies that we can create two or more constructors with the same name but different parameters.
Let us overload a default constructor and a parametized constructor.
Let us overload two parametized constructors.
(1.) Write a program for a scenario/case/example where you would:
(I.) Implement any of the constructors that we discussed.
(II.) Use a combination of at least two different data types for the class fields.
This implies that you should have at least two class fields of different data types.
(2.) Write a program that overloads at least two constructors.
(1.) Write a different constructor that will give the same output as the constructor used in the initial post.
For Questions $(1.)$ and $(2.)$
The questions involve Desktop Applications
If you would like to know how to develop desktop applications with Java and Swing, please review
Module 1 of the Beginning Java course.
Even if you do not attempt these questions, it is important to learn that module because desktop applications would be
required for your Midterm Project and your Final Project.
No worries, Mr. C is here to help.
(1.) Develop a desktop application titled: Object-oriented Programming Basics
The application should include at least one button that:
(I.) Implements any of the constructors that we discussed.
(II.) Use a combination of at least two different data types for the class fields.
This implies that you should have at least two class fields of different data types.
(2.) Develop a desktop application titled: Object-oriented Programming Basics
The application should include at least one button that overloads at least two constructors.
I am more interested in the functionality.
However, I am also interested in the design/graphics/aesthetics.
Make a good design.
(3.) Textbook Question: Question $(12.)$ on Page $165$ of your textbook.
(4.) Textbook Question: Case Problem: Question $(13.)$ on Pages $166$ of your textbook.
Students will:
(1.) Discuss the concept of Encapsulation.
(2.) Discuss the properties of a class
(2.) Implement the various properties in a class.
(3.) Develop a console application that implements classes, objects, constructors, and properties.
(4.) Develop a desktop application that implements classes, objects, constructors, and properties.
get, get accessor, getter, set, set accessor, setter, void, parametized constructor, exceptions, throw an exception, encapsulation, reference, dependency, event, event handler, backing store, solution, container, event, event handler, tuple, trigger, behavior
(1.) Textbook Chapter
(2.) Java Modifiers and Java Encapsulation by W3Schools
(3.) Object-Oriented Programming Concepts by Oracle
(4.) Designing a Swing GUI in NetBeans IDE
by Apache NetBeans
(5.) Learning Swing with the NetBeans IDE
by Apache NetBeans
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type Object-oriented Programming in Java and/or OOP in Java in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type Object-oriented Programming in Java and/or OOP in Java in the search bar and view/read the results.
We used the public access modifier in Module $1$
We have other access modifiers.
By default, codes are only accessible in the same package.
Access Modifier | Accessibility Level |
---|---|
public | Access is not restricted. The class member can be assessed outside the class that it was created. |
private | Access is limited to the containing type. The class member can only be assessed within the class it was created. |
protected | Access is limited to the containing class or types derived from the containing
class. The class member can be assessed within the class it was created, or in a class that is inherited from the class that it was created. |
Let us do some examples.
We shall demonstrate the use of private access modifier.
Say I want to greet a specific student in my class with my mother tongue: the Igbo language.
If you point your mouse at the error, it reads: greeting() has private access in Encapsulation
You also see the message at the bottom left corner of your IDE (as seen in the screenshot).
If you click the light bulb at the beginning of that line, and double-click on the "recommended message", you
will notice that the IDE has removed the private access modifier in the method: greeting
Go ahead and run the program.
Teacher: Notice the error?
Student: Yes. I guess it's because the welcome attribute is private?
Teacher: That is correct.
The greeting method cannot access the private welcome
Student: So, we have to remove the private modifier
Also what is the meaning of the greeting?
Teacher: The greeting means: Welcome to our School
Yes we can remove the private modifier and the program will run.
However, every student will hear the greeting and some students will not understand the language.
Some may have issues with it.
Student: Well, just explain the meaning. Translate it for all the students.
Teacher: I want to greet only the student with the Igbo language.
What should I do?
Also, have you heard of Cryptology?
Cryptology is the science of secret messages.
If you don't want everyone to access that message, you encode the message with a private key, and give the key to
any person you want to decode the message.
So, in this case; this is what we can do.
Welcome to ...
Encapsulation
Encapsulation is the combination of fields, properties, methods, and events of an object in a class (capsule).
In other words, keep all the data and program logic in one place.
It is used to hide sensitive data from users.
An important part of Encapsulation is the use of properties.
A property is typically a public class member that can read, write, or
compute the value of a private field.
Just like a constructor, a property is also a method.
So, it needs an access modifier.
That access modifier typically, must be public.
The accessors are the: get accessor and the set accessor.
In other words, the get and set parts of a property are called accessors.
The main objective of using Properties is for encapsulation in terms of hiding sensitive data from users.
Properties in Java:
(1.) Typically have a public access modifier.
(2.) Comprises of the get and set accessors.
The get accessor is also known as the getter
The set accessor is also known as the setter
The get property accessor is used to: read, compute; then return the property
value.
It gets and returns that private field/class member.
The set property accessor is used to perform some data validation, compute; then
write or assign that private field/class member to a value.
(3.) Can be read-write if it has both the get and set accessors.
(4.) Can be read only if it has only the get accessor.
(5.) Can be write only if it has only the set accessor.
Write-only properties are mostly used to restrict access to sensitive data.
Recall:
(1.) Constructor has the same name as the Class.
(2.) Class names are uppercase or Pascal-case.
(3.) Field names are lowercase.
In that regard, it is recommended that Property names be uppercase of the field names.
The syntax for the Getter is:
public dataType propertyName() { return privateAttribute; }The syntax for the Setter is:
public void propertyName(dataType newName) { privateAttribute = newName; }So, let us solve this problem by using Properties.
Please review the BMI information on these two government websites [from the Center for Disease Control and Prevention (CDC) and the National Heart, Lung, and Blood Institute of the National Institutes of Health (NIH)]
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC and
Calculate Your BMI - Standard BMI Calculator
As at today, the 3rd day of September, 2020; the BMI information on both websites are:
NIH website
Calculate Your BMI - Standard BMI Calculator
CDC website
About Adult BMI | Healthy Weight, Nutrition, and Physical Activity | CDC
$ BMI = \left(\dfrac{weight}{height * height}\right) * 703 \\[5ex] weight\:\:is\:\:in\:\:pounds (lb) \\[3ex] height\:\:is\:\:in\:\:inches (in) $
$ BMI = \left(\dfrac{weight}{height * height}\right) \\[5ex] weight\:\:is\:\:in\:\:kilograms (kg) \\[3ex] height\:\:is\:\:in\:\:meters (m) \\[3ex] $ If you need help with conversion of units, please review the Tables and Examples in Measurements and Units
Teacher: What do you notice in both websites?
Student: They both have the information on the BMI.
In addition, the CDC website has information for both Adult BMI and Child & Teen BMI among others.
The NIH website has recommendations among others.
Teacher: That is correct. What else?
Student: They have the BMI calculator.
Teacher: Did you notice any difference in the calculator on both websites?
Student: The NIH website has BMI calculator for both Standard and Metric versions.
The CDC website has the BMI calculator for only the Metric version.
Teacher: Did you notice any issue/concern about the BMI information?
Student: Not really. Why?
Teacher: So, this is what we are going to do.
Let us develop the BMI calculator.
That calculator will calculate the BMI.
Then, we shall interpret that BMI, and make a recommendation.
.
The CDC website gave us the formula for calculating the BMI. So, we shall use it.
As you can see, our calculator would have to use conditional statements for the interpretation and recommendation.
But, here is the issue.
Student: Wait, I think I see the issue.
The issue is with the domains.
Teacher: Correct!
Anyone having a BMI between $18.5$ and $24.9$ both endpoints included has a Normal weight.
This is: Normal weight: [18.5, 24.9]. It is a closed interval (relate with Mathematics).
So, the Overweight range for the BMI should be the weight greater than $24.9$, (rather than beginning from $25$) and ending at $29.9$
For the Overweight range, the first endpoint is not included, but the second endpoint is included.
This is: Overweight: (24.9, 29.9]. It is a half-open half-closed interval (relate with Mathematics)
Teacher: Do you know why this would be a problem if the programmer does not fix these issues before developing the calculator?
Student: Yes. Because there would not be any interpretation for anyone whose BMI is between $24.9$ and $25$
But, I do see that the BMI information is for values rounded to one decimal place.
Teacher: That is correct.
And we shall develop our calculator to round to one decimal place.
But, it is important we fix the issues.
What if we do not want to round?
Look at the two examples on the CDC website. The BMI values were rounded to two decimal places.
If we developed our calculator to round to two decimal places with the information on those websites "as is"; then we would not have the interpretation and recommendation for those two examples ($24.98$ and $24.96$) because those values are greater than $24.9$ but less than $25$.
Student: That makes sense.
So, the last one: Obese should be BMI greater than $29.9$, rather than greater than $30$?
Teacher: That is correct.
So far, we discussed:
(1.) Methods (Functions) in Java Programming
(2.) Introduction to Object-oriented Programming (Classes, Constructors, and Objects) in Module 1.
(3.) Encapsulation in this module: Module 2.
Let us apply what we learned so far.
We shall develop a console application and a desktop application for the Body Mass Index (BMI) calculator.
(1.) The program should accept user inputs of:
(I.) First name
(II.) Last name
(III.) Weight
(IV. Height
(2.) The program should output the:
(A.) BMI value
(B.) Interpretation
(C.) Recommendation
(3.) The program should address user-input errors of non-positive numbers for the weight and the height.
Inform the user.
Then, exit the program without causing it to crash.
(1.) We shall create a new project: AdvancedJavaModule2
As we discussed earlier, the The project name is the name of the public class: AdvancedJavaModule2
The project name is also the name of the Java file: AdvancedJavaModule2.java
The name of the namespace is: advancedjavamodule2
(Notice the name is all lowercase of the Java file name)
We shall create another Java file under the same package.
We demonstrated this concept in Module 1.
That class will be the Main class because it will contain the main method.
Let us name that class: BodyMassIndex.java
(2.) Because the first name and the last name is not needed in the calculation, we shall ask for the user input
of the first name and last name in the main method
The main method is in the BodyMassIndex public class
The BodyMassIndex public class is in the BodyMassIndex.java file
Teacher: You know something I learned in America...as regards dating?
Student: What is it?
Teacher: You should not ask a woman her weight.
Student: LOL. Is that all you learned?
Teacher: Another thing is that you should not ask a woman her age.
But, a woman can ask a man his age.
Student: That is correct. In America, you do not ask a woman her weight or her age.
Teacher: Is that not double standard?
Anyway...B2B (back to business)
(3.) We shall create two fields: weight and height for our class: AdvancedJavaModule2
Because we shall associate the weight and height with the user's first name and last name, we shall declare
these fields as private.
(4.) We shall create public properties for these private attributes so we can access them.
Remember that method names in Java should begin with uppercase letter.
Property is a special method.
So, the properties should be the uppercase beginning letters of the variables.
(5.) We shall create a parametized constructor that will initialize the class attributes.
Assign the attributes to the constructor parameters.
(6.) We shall create a method: BodyMassIndexDetails
This method is necessary to calculate the BMI.
We need to throw an exception to ensure that only positive values are entered for the user input weight and
height.
Zero and negative values should not be allowed.
No worries. We shall disuss Exception Handling in details in another module.
For now, please learn how to do it in this application.
In addition, we shall interpret the BMI and make recommendation based on the calculated BMI value.
We shall create three more variables here. These variables are local variables.
For local variables that are directly calculated from the class fields, we do not need to initialize.
However, for local variables that are not directly calculated from the class fields,
we must initialize those variables.
(7.) Go to the main method in the BodyMassIndex public class class and ask for user input of the
first name, last name, weight, and height
We will declare two more variables for the: weight and the height in the main method.
We shall use that weightPounds and heightInches as our variables.
Notice that they are the constructor parameters we used in the AdvancedJavaModule2 class
In other words: our constructor parameters in the AdvancedJavaModule2 class are the
weightPounds and heightInches variables in the BodyMassIndex class
Create the object: calculateBMI
Use that weightPounds and heightInches as the arguments
Display your summary and make it look nice.
To use a background color in the Netbeans console window:
\033[43m is the code that gives a yellow background.
Use the object to call the method.
(8.) Test your program for each piece/case.
In other words, test your program to ensure that the calculation, interpretation, and recommendation is correct
for all the BMI options.
You may also test the examples on the CDC website.
(9.) Test your program to check for user input errors.
In other words, test your program for the Exceptions.
Please see the images.
Review the comments.
Exceptions:
Please review the Teacher-Student scenario
Student: Mr. C, why do we need to develop desktop application?
Can't we just focus on console applications?
Teacher: Desktop applications are required for several DB assessments and for your Midterm Project.
It is optional for your Final Project.
It is important you learn to develop them.
Student: But, why?
Teacher: These are the reasons:
(1.) GUIs (desktop applications) cover a significant part of Number (1.) of the Student Learning Outcomes of the Beginning Java course.
They also cover some parts of Numbers (2.), (3.), and (4.) of the Beginning Java course.
(2.) You can run the executable JAR (.jar) file of a desktop application in any desktop/laptop that has
Java installed in it (both Windows and Mac)
Student: What are executable JAR files?
Teacher: Good question.
When you develop a Java program with Swing components such as the one we shall develop in a moment,
an executable file can also be developed. It is a file that is run on your computer to execute (do) something on your computer.
When you download and install a program on your computer (Windows users), it is normally seen as install.exe,
setup.exe or other "something".exe with the word, Application used to describe it.
In our case, it is going to be a standalone file with the jar extension described by
Executable Jar File that when downloaded in any desktop, can run when double-clicked.
Usually, you will get a warning from your computer not to download it because it can destroy your computer.
If you do not know the source/origin of the executable file, do not download it.
But in this case, we shall develop the program so we know it is safe.
When we develop the program, we need to follow these steps to locate the executable file.
Double-click: Application folder → dist → Application.jar
That Application.jar file is the executable file.
You can download it (no worries, it is safe), save it on your desktop, and run it on your desktop whenever
you want to.
Student: If I copy it to another desktop, will it run?
Teacher: Yes, it will run on any desktop provided that Java is installed on that computer.
That is the nice thing about it.
Student: Just that file?
It will run with all the functionality?
Without copying the entire folder?
Teacher: That is correct.
Click these links and review some of the desktop applications done by my students:
VB desktop applications and
C# desktop applications
These will run without any additional download.
Desktop applications are much better than console applications.
If you click the PROJECTS tab of this website and review the console applications done by my students,
you will realize that you need to type at least one command in the console before you can run the application.
If you review the PROJECTS (console applications) done by my C++ students,
it may require some program downloads to run on your machine (laptop/desktop).
You do not have to worry about typing commands or extra downloads when running desktop applications.
Student: Pretty cool.
Teacher: Yes, it is.
(3.) Assume you are working in a developing country (in Nigeria for example), you have a computer but no
internet service, and you really need to develop applications for the projects you are working on;
developing desktop applications is highly recommended in such cases because you do not need the Web/Internet
to run them. All you need is a laptop or desktop.
Student: But, I'm not working in Nigeria.
Neither do I intend to work there.
Teacher: What if you work for a multinational company and your compnay transfers you to work there?
What if you decide to join your church or organization on a charity mission trip?
(4.) Have you heard that the only thing that is not safe is anything on the Web?
Well-developed desktop applications minimizes your use of web and mobile applications, thereby minimizing cyber crimes.
There are limitations with desktop applications.
But, there are advantages too.
One of the advantages of Java is the developement of Desktop aplications.
Let us a Body Mass Index (BMI) desktop application. 😊
As is the case for development of desktop applications, the three basic things to do are:
(1.) Create the user interface
(2.) Set the properties.
(3.) Write the program code.
$(1.)$ JFrame Form
(A.) Add a JFrame Form
(B.) Adjust the form in the Design area
(C.) Set the font property of the form to:
Font: Times New Roman Font Style: Plain Size: $16$
(D.) Set the title property to Body Mass Index (BMI) Application
$(2.)$ Label
(A.) Add a label aligned to the left
(B.) Change thetext Property to: First Name at the Properties window
(C.) Press the ENTER key
(D.) Adjust the size
Go to the Properties window and change the font property to: Font: Times New Roman Font Style:
Plain Size: $16$
Let us run it to see how it looks before we continue.
Notice we unchecked that box to Create a Main Class when we were creating the Project.
This is because we want the JFrame Form: now titled: bodymassindex.BMIApplication.java to be the Main Class.
Close the app.
Close it again.
Let us change it to font size of $24$ and run it again.
$(3.)$ Text Field
(A.) Add a text field aligned to the right
(B.) Delete the text property: jTextField1
(C.) Go to the Properties window and change the font property to: Font: Times New Roman Font
Style: Plain nbsp; Size: $24$
(D.) Align the user-entered text to the center.
In the Properties window, set the horizontalAlignment property to CENTER
(E.) Right-click the text field and Change Variable Name to firstNameTextField
$(4.)$ Duplicate the First Name label by right-clicking the label and clicking the Duplicate option.
Change the text property to Last Name
$(5.)$ Duplicate the Last Name label.
Change the text property to Weight
$(6.)$ Duplicate the Weight label.
Change the text property to Height
$(7.)$ Duplicate the firstName text field.
Change Variable Name to lastNameTextField
$(8.)$ Duplicate the lastName text field.
Change Variable Name to weightTextField
$(9.)$ Duplicate the weight text field.
Change Variable Name to heightTextField
$(10.)$ Align the labels and the text fields accordingly.
Adjust as needed.
$(11.)$ Copy the Weight label, paste it, and move it to the right of the weight text field.
The label is for the unit of the weight.
Change the text property to pounds
Adjust and align.
$(12.)$ Copy the Height label, paste it, and move it to the right of the height text field.
The label is for the unit of the height.
Change the text property to inches
Adjust and align.
$(13.)$ Button
(A.) Add a Button.
Align the left hand side to the left, and Adjust.
Change the font property to: Font: Times New Roman Font Style: Plain nbsp; Size: $24$
Change the text property to Calculate BMI
Change Variable Name to calculateButton
(B.) Add another button in the form.
Adjust.
Change the font property to: Font: Times New Roman Font Style: Plain nbsp; Size: $24$
Change the text property to Reset
Change Variable Name to resetButton
(C.) Add another button in the form.
Align the right hand side to the right and Adjust.
Change the font property to: Font: Times New Roman Font Style: Plain nbsp; Size: $24$
Change the text property to Exit
Change Variable Name to exitButton
$(14.)$ Text Area
Add a text area.
The output will be displayed in the text area.
Align to both ends: the left hand side and the right hand side of the controls; and Adjust.
Change the font property to: Font: Times New Roman Font Style: Plain nbsp; Size: $24$
Change Variable Name to resultTextArea
The Design Area is:
The Inspector Area is:
The Palette (ToolBox Controls) are:
The Property Editor is:
Now, onto the Coding part....
(1.) Double-click the Calculate BMI button to go to the Source Area
Write the code that will display the result in the text area.
(2.) Create a new Java class: BMIApp under the same package
The Property Editor is:
(3.) Copy all the code in the "other" class (not the Main class): AdvancedJavaModule2.java that we did for
the Console Application.
Do not include the public class name.
Paste the code inside the BMIApp class
Change the constructor name to the BMIApp
Make some changes regarding the results.
In other words, use a StringBuilder class.
This is necessary because we want to print the results from the BodyMassIndexDetails method in the
BMIApp class to the text area in the BMIApplication class.
(4.) Open the Main class for the Console Application: BodyMassIndex.java
Copy some code.
Paste the code in the Main method in the Desktop Application class: BMIApplication.java
Modify the code.
(5.) Double-click the Reset button to go to the Source Area
Write the code that will clear all entries in the text fields.
(6.) Double-click the Exit button to go to the Source Area
Write the code that will close the application.
Please review the screenshots and the comments.
(1.) Test the program for each condition (the conditional statements for the BMI)
(2.) Test the program for Exceptions (exception handling).
Publish our GUI as a Desktop Application
This means that we have to create an executable JAR (Java ARchive) file.
To do this, we need to Clean and Build Project (Clean and Build the Introduction project) or press the
Shift + F11 keys on
your keyboard.
When this is done, the dist folder is created.
That dist folder contains the Executable JAR file.
Please review the screenshots.
Student: I have a question.
If I decide to make some changes to the code, will those changes be automatically reflected in the app
even though the app has been published?
Teacher: Good question.
Whenever you make changes to your program code, then you will need to Clean and Build Project again.
An updated executable jar file will then replace the previous one.
So, you will need to re-download the new file.
For example: let us make a change to the title of the application.
Compare the title of the application on the screenshots with the title of the application on the JAR executable file
Did you notice the change?
The new file was downloaded after making the change, and doing Clean and Build Project
This is the BodyMassIndexApplication.jar executable file
You may click the link to download and run it. No worries, it is safe.
It is a desktop application.
If you have Java on your computer (PC or Mac desktop/laptop), click the file and run the application directly on your desktop.
For Questions (1.) and (2.)
(I.) Consider any concept/scenario that uses conditional statements.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Use a class you created.
(IV.) Use at least one private field.
(V.) Use properties that should access that private field.
(VI.) Use at least one method.
(VII.) Include some checks for user input errors.
(VIII.) Test your program and display the result/output for each condition.
(IX.) Test your program for user-input errors.
(X.) Submit all the screenshots in your DB 2 forum on Blackboard.
(1.) Develop a console application for your concept.
(2.) Develop a desktop application for your concept.
(1.) If your colleague developed only a console application, develop the desktop application for that concept.
(2.) If your colleague developed only a desktop application, develop the console application for that concept.
(3.) Other substantive responses.
For Question (1.)
(I.) Consider any concept/scenario that uses conditional statements.
Use at least two (two or more) different conditions.
The BMI Calculator has four different conditions.
But, please use any application that has at least two different conditions.
(II.) Accept user input(s).
(III.) Use a class you created.
(IV.) Use at least one private field.
(V.) Use properties that should access that private field.
(VI.) Use at least one method.
(VII.) Include some checks for user input errors.
(VIII.) Test your program and display the result/output for each condition.
(IX.) Test your program for user-input errors.
(X.) Submit all the screenshots in your DB 2 forum on Blackboard.
(1.) Develop a console application and a desktop application for your concept.
One application will count for DB Post.
The other application will count for DB Response.
Please specify which one should count for DB Post or DB Response.
(2.) Develop a console application for an extension of my concept (the BMI application).
I did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
(3.) Develop a desktop application for an extension of my concept (the BMI application).
I did the application for the United States System (Customary System).
Extend the application by developing the calculator for the International System (Metric System).
The formula is on the screenshot.
Ask the user which system he/she wants to use to calculate the BMI.
Your desktop application should have the dropdown list for both systems, but should be null be default (using a ComboBox)
Alternatively, you may choose to use Radio Buttons.
Based on the user's selection, display the appropriate units for the weight and the height, as well as the output.
Test all the conditions for both systems.
(4.) Textbook Question: Case Problem: Question $(1.)$ on Pages $167$ and $168$ of your textbook.
(5.) Textbook Question: Case Problem: Question $(2.)$ on Pages $168$ and $169$ of your textbook.
(1.) Textbook Chapter
(2.) Java Exceptions (All) by Oracle
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type Java Exception and/or Java Exception Handling in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type Java Exception and/or Java Exception Handling in the search bar and view/read the results.
The midterm project is designed to assess your knowledge of Object-oriented Programming in solving real-world problems.
It is a Piecewise Function application.
Any other application will not considered.
Please:
(1.) Visit my website on: Piecewise Functions
(2.) Read the Story to understand the idea of Piecewise functions.
(3.) Read the Overview of Piecewise Functions for more understanding of Piecewise
functions.
(4.) Study the Applications of Piecewise Functions
(5.) Review the Project Examples. Ensure you follow all the instructions and directions.
(6.) Review the Midterm Project rubric for your course.
(7.) Complete the Midterm Project for your course.
(8.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(9.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Midterm Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(10.) Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
If you wish to save some time for research:
Please review the Piecewise Function projects done by my previous students.
The direct link of the verifiable websites are included.
(I.) VB.NET Projects
(II.) C# Projects
(III.) C++ Projects
(IV.) Java Projects
You may not do any same application done by any of my previous students for Java
You may do any Piecewise Function application not done by any of my previous students for Java.
If you are not sure what project you may or may not do, please contact me via the school email.
inherit, inheritance, behavior, data, class members, colon symbol :, parent class, base class, super class, child class, derived class, extended class, sub class, ancestors, single inheritance, multilevel inheritance, transitive inheritance, extends keyword, @Override keyword, abstraction, abstract keyword, virtual function, abstract class, abstract method, polymorphism, lambda expression, interface, implements keyword, enum, enumeration,
Students will:
(1.) Discuss the inheritance of a class.
(2.) Discuss polymorphism in object-oriented programming.
(3.) Write programs that demonstrate the inheritance of a class.
(4.) Write programs that demonstrate polymorphism.
(1.) Textbook Chapter
(2.) From: Java Inheritance to: Java Enums by W3schools
(3.) Interfaces and Inheritance (All: From: Interfaces to: Questions and Exercies) - The Java Tutorials by Oracle
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type Java Inheritance and Polymorphism in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type Java Inheritance and Polymorphism in the search bar and view/read the results.
There are three primary characteristics/pillars of object-oriented programming:
(1.) Encapsulation
(2.) Inheritance
(3.) Polymorphism
A teacher, Mr. C with his three students: Student $1$, Student $2$, and Student $3$
The students are dual enrolled high school students.
They are bold and smart.
They are taking a Computer Science course with Mr. C
Teacher: Today, we shall be discussing Inheritance
Student $1$: Is this a Biology class?
Teacher: Why do you ask?
Student $2$: Why do you answer questions with questions?
Teacher: Typical of Nigerians 😊
It saves you from getting into trouble.
Student $1$: I asked because we are studying Genetics.
Teacher: Interesting.
So, we can use some interdisciplinary knowledge from both courses.
My first question is:
What did you inherit from your parents: Dad, Mom, Grand Dad, Grand Mom (Father's side), Grand Dad, Grand Mom
(Mother's side), several generations on both sides, atavism?
Student $2$: What do you mean by atavism
Student $3$: It's a reappearance of an ancestral trait.
For example: Remember those Nigerian parents (both of them are Black) that gave birth to a white baby girl?
One of the reasons the doctors gave was dormant white genes which entered both of the female's parents' families
long ago.
That is atavism.
You can read the story online. Wait: here is the link from CBS News:
(https://www.cbsnews.com/news/white-baby-shocks-black-parents-medically-possible/)
Student $1$: CBS News? LOL
Teacher: Hey, do not say what you want to say.
This is not politics.
Student $1$: And what if I do?
Student $3$: Some other news sources have it as well.
Teacher: Okay guys, you have not answered my question.
Student $2$: Well, as you can see: I have blonde hair and blue eyes.
But surprisingly, my parents have brown hair and brown eyes.
Why is that?
Student $1$: Your parents have the dominant brown hair and brown eyes genes and the recessive blond hair
and blue eyes genes.
They passed those recessive genes to you.
Student $2$: Interesting.
But, if I want my children to have those dominant brown hair and brown eyes genes, what should I do?
Student $1$: Let me just invite you to our Biology course so you ask those questions.
I am still learning.
But, just pray for it. Do not do anything to try to disrupt nature.
Teacher: Okay, get back on track to my questions.
Student $3$: I inherited intelligence from my parents.
Student $1$: So, we had this argument in class: Is intelligence acquired or inherited?
Is it by nature or nature or both?
Teacher: Intelligence is both nature and nurture though it is more of nurture.
Student $1$: What are your reasons, Sir?
Teacher: You have two Nigerian parents, did not attend school did not have any formal education; yet
their children are the best graduating medical students.
Student $1$: Well, the fact that they did not attend school does not mean that they are not intelligent.
Someone who is not literate can still be intelligent. I think intelligence is wisdom.
Student $3$: I inherited tallness from my Mom.
My Mom is tall and my Dad is of average height.
Teacher: I am still waiting for your answer.
Student $1$: Who? Me?
Teacher: Yes of course.
Student $1$: I think I inherited my temperament from my Dad.
Teacher: Bold. Reactive (not proactive). High activity level. Persistent.
Student $1$: You got it.
But, you do know environmental factors contribute as well.
Teacher: Yes I know.
Just like Intelligence, Temperament is both nature and nurture. However, it is more of nurture.
Student $1$: Now, back to you, Mr. C
What did you inherit from your parents?
Teacher: Oh come on.
Can't you see it?
Everyone is looking at me.
Student $1$: Meaning?
That I am a very handsome man.
Everyone starts smiling/laughing
It's good to laugh and be relaxed before we start learning some codes.
Student $1$: We are looking at you because you are the professor.
Teacher: And because I am very handsome.
Alright, B2B...
Everyone says: Back to Business
So as you can see (based on our discussion), one can inherit traits from the Dad, Mom, Mom and Dad, grandparents, or
even ancestral traits.
So far:
In your previous course: the Beginner's course; we discussed
(1.) Method/Function
In the previous modules for this course, we discussed:
(1.) A class
(2.) Constructor
(3.) Property
Say that we created a class: Class $A$ with some members: fields, properties, and methods
We want to create another class: Class $B$ and use the members from class $A$ and also use additional members
Keep in mind that class members includes fields, properties, and methods.
Rather than create Class $B$ and define all those members from Class $A$, we can create Class $B$ as a child of
Class $A$ so that it inherits the class members from Class $A$ and then create the additional members for it.
We can also create Class $C$ to inherit some of the properties of Class $A$ and also some of the properties
of Class $B$
So, you can see it this way:
Class $A$ as the parent
Class $B$ as the child
Class $C$ as the grandchild
Remember one inherits the genes of grandparents and great grand parents and so on and so forth. The amount
depends on the percentage or fraction. (which you discuss in Genetics).
Welcome to Inheritance.
Inheritance is the ability of a class to inherit the members of
another class.
The class whose members are inherited from another class is known as the base class or
parent class or super class
The class that inherits the class members from another class is known as the derived class or
child class or extended class or sub class.
So, this is seen as:
Base class and Derived class OR
Base class and Extended class OR
Parent class and Child class OR
Superclass and Subclass (Compare to Superset and Subset in Algebra)
(Please get used to these words because we shall be using them interchangeably.)
Superclass and Subclass are preferred terms for the Java programming language.
The main purpose of inheritance is to reuse, extend, and modify the class members of a parent class by
the child class.
It allows one to define a child class that reuses (inherits), extends, or modifies/overrides the behavior of a parent class.
When a class is derived from a base class, the derived class implicitly gains all the members of the base
class, besides its constructors and finalizers.
The derived class reuses the code in the base class without having to reimplement it.
You can add more members in the derived class.
The derived class extends the functionality of the base class.
The ancestors of a derived class are the superclasses from which the subclass is derived.
(1.) The inheritance of a base class from a derived class is achieved using the extends symbol.
The syntax is:
public class SubClass extends SuperClassRecall the BodyMassIndexApplication GUI project we developed in Module 2.
Let us discuss some advantages of Inheritance.
(1.) Code Reusability: As seen in the previous examples, we reused the class fields of the base class.
Inheritance is like the DRY (Don't Repeat Yourself) of programming because some class members of the base
class are reused.
Reusability leads to reduced development and maintenance costs.
(2.) Code Extensibility: Inheritance allows for modification and extension of code.
As seen in the previous examples, we modified and extended the fields that was inherited from the base
class, in the derived class.
(3.) Creation of Class Libraries: Inheritance facilitates the creation of class libraries.
(4.) Access to protected class members of the base class:
So far, we have:
(a.) Used the public access specifier.
(b.) Used the private access specifier.
Recall that we had to use Property to access a private class field.
But, what about the other access specifier: protected. We have not used it.
We shall use it in this module.
Recall that in the: protected access specifier: Access is limited to the containing class or types
derived from the containing class.
The class member can be assessed within the class it was created, or in a class that is inherited
from the class that it was created.
The protected class members are similar to private class members. However, they can be
inherited.
So, we shall be using the protected access specifier for any class member that we want to
encapsulate.
Please note that: we still need to use Properties to access protected class members because technically,
they are still 'private'.
The only difference is that they can be inherited by derived class while private class members cannot be
inherited.
So, they will be inherited. But, we shall use Properties (setter and getter) to access them.
Let us demonstate the use of the protected access specifier.
Let us do some math calculations.
Simple Interest and Amount Calculations
Please review Questions (5.) and (9.) and the solutions on the Solved Examples on
Simple Interest website:
(www.finance-calculators.appspot.com/simpleInterestApplications.html)
Let us calculate the simple interest and amount for several customers.
We shall use Inheritance to solve that Question for several students.
We shall make the interest rate of the financial institution and the time to be public, but make the first
names of the customers and the principal (sum of money deposited) to be protected.
Please review the screenshots and the comments.
(1.) Coupling of the base class and the derived class: The derived class is dependent on the base class to
the degree that any change in the base class affects the derived class.
Imagine if one deletes a class member of a base class that is also used in the derived class.
For instance, in our demonstration of Multilevel Inheritance; if one of the properties of the Quadrilateral is
deleted, the program will not run.
(2.) Execution time (Run time): It takes more time for an inherited method to execute when compared to a
method that did not use inheritance.
One can write a program that uses a class to calculate the simple interest and amount of an investment without using
inheritance.
(3.) Depending on the compiler, unused base class members is a waste of memory: When a derived class inherits
a base class, it may or may not use all the inherited class members of the base class.
In the event that any base class member is not used in the derived class, it leads to a waste of resource/memory
allocated to that class member. This typically depends on the compiler.
Notice that in our examples, we did not use all the fields of the base class.
Abstraction is the process of hiding sensitive data while exposing only the required properties and methods.
Compare it to a situation where we have a private class field, but use a public property to access that field
(the Get and Set accessors).
Abstraction is done using:
(1.) Abstract class
(2.) Interface
An abstract class is a class that:
(1.) Is declared using the abstract keyword.
(2.) Cannot be used to create objects.
In other words, it cannot be instantiated directly using the new operator.
Because it cannot be used to create objects, it cannot have a constructor.
(3.) Can be used as a superclass or a subclass. Most times, it is used as a superclass.
It must be inherited by another class.
But, it can also inherit a class.
When an abstract class inherits a virtual method from superclass, the abstract class can override the
virtual method with an abstract function (abstract method).
(4.) May contain abstract members (including abstract methods).
If it contains an abstract member, that member must be declared with the abstract keyword.
(5.) May contain non-abstract members.
The reason for using an abstract class is to provide a common definition of a superclass that multiple derived classes
can share.
For example: an abstract class can be used as a parameter to several functions of a class library, and require
programmers using that library to implement the class by creating a subclass.
An Abstract function is a function that:
(1.) Is declared using the abstract keyword.
(2.) Have no implementation.
It does not have a body.
Hence, it is followed by a semicolon rather than the normal method block.
The *implementation* of an abstract method is provided by the subclass that inherits it.
Note that the method of the subclass must override (using @Override keyword) that abstract method in order to
implement it's own method (because the abstract method does not have any implementation).
(3.) Must be used only in an abstract class.
A concrete class is a nonabstract class that can instantiate objects.
In other words, it can be instantiated directly using the new operator.
Teacher: Remember we discussed earlier that C# does not support multiple inheritances.
Student: Yes.
Java does not support multiple inheritances. But C++ does.
Teacher: That is correct.
However, Java supports multiple interfaces.
So, if you want to demonstrate multiple inheritances with Java, you can do so with multiple interfaces as
the parents.
An Interface is like an abstract base class that:
(1.) Is declared using the interface keyword.
(2.) Can contain instance methods, properties, events, indexers, or any combination of these member types.
(3.) Cannot contain instance fields, instance constructors, or finalizers.
However, it may contain static constructors, static fields, constants, or operators.
(4.) Contains definitions for a group of related functionalities that a non-abstract class or struct must implement.
Struct is not covered in this course.
(5.) Is used to simulate inheritance for structs because structs cannot inherit from another struct or class.
Struct is not covered in this course.
(6.) Is inherited using the implements keyword rather than the extends keyword
Multiple interfaces can be inherited.
Java supports the inheritance of multiple interfaces, but not the inheritance of multiple classes.
(7.) Is recommended (not required) that the identifier begins with an uppercase I
For this course, we shall use identifiers that begin with an uppercase I (following C# syntax).
(1.) An interface contains only abstract public members.
Any class that implements an interface must implement all the members of that interface.
An interface may define default implementations for some or all of its members.
(2.) An interface cannot be used to create objects.
In other words, it cannot be instantiated directly using the new operator.
The members of an interface are implemented by any class ot struct that implements the interface.
To implement any member of an interface, the corresponding member of the implementing class must be public,
non-static, and have the same name and signature as that interface member.
(3.) A class or struct can implement multiple interfaces.
Further, a class (not a struct) can inherit a base class and also implement multiple interfaces.
Teacher: Let us demonstrate the inheritance of multiple interfaces.
We shall use the same example that we used when we demonstrated Multiple Inheritance in C++
Student: You mean the Zoology example for the dog breeds?
Teacher: Yes.
Multiple Interfaces
Literally: poly means many and morphs means forms; so polymorphism means
many forms
Polymorphism is the ability of classes to:
(I.) Invoke the methods of a derived class by referencing a base class at run time and
(II.) Implement different methods called by the same name at compile time
There are basically two kinds of polymorphism:
(1.) Dynamic Polymorphism
(2.) Static Polymorphism
This polymorphism:
(1.) Occurs at run time
(2.) Also referred to as late binding polymorphism because the decision regarding the method to be called
is made at run time.
(3.) Overrides the method of a base class by using the same name and parameters of that method in a
derived class in order to perform a different task. (Method Overriding)
For this to occur, the same method in the subclass must use the @Override keyword.
Recall that the methods in the subclasses have the same name/identifier with the method in the superclass.
We want to use the method in the subclass to override the method in the superclass. Hence, we use the @Override
keyword.
Let us demonstrate Dynamic Polymorphism
Back to Geometry: Quadrilaterals
A Quadrilateral is a four-sided polygon.
These figures are Quadrilaterals.
(1.) Square
(2.) Rhombus
(3.) Rectangle
(4.) Parallelogram
(5.) Kite
(6.) Trapezoid
We shall calculate the perimeter of these quadrilaterals.
The formulas for calculating the perimeters of quadrilaterals are found here:
Mensuration Formulas
(www.samuelchukwuemeka.com/Mensuration/formulas.html)
The website also contains the calculators for calculating perimeters.
You may test the output of this program with the Mensuration Calculators
on the website.
We shall list the parameters used for calculating the perimeters of the quadrilaterals.
The parameters are the class fields of the base class: Quadrilateral.cs
Main Class: Polymorphism.java
Superclass: Quadrilaterals.java
Subclass: Square.java
Subclass: Rectangle.java
Subclass: Rhombus.java
Subclass: Parallelogram.java
Subclass: Trapezoid.java
Subclass: Kite.java
To calculate the perimeter of a:
(I.) Square and Rhombus: only a side is needed.
So, we shall define side as one of the class fields of the Quadrilateral
(II.) Rectangle and Parallelogram: the length and the width is needed.
So, we shall include length and width as class fields of the Quadrilateral
(III.) Kite: A kite has two pairs of equal sides.
We shall define them as side1Kite and side2kite and include them as class fields of the Quadrilateral
(IV.) Trapezoid: A trapezoid has no equal side.
The Quadrilateral class fields for these sides are: side1Trapezoid, side2Trapezoid, side3Trapezoid,
and side4Trapezoid
The other class fields we need for the Quadrilateral.cs class are the fields that define the perimeters for each
quadrilateral.
Let us demonstrate Dynamic Polymorphism (Polymorphism at Run-time)
Please review the screenshots and the comments.
Dynamic Polymorphism (Polymorphism at Run-time)
Lines 30-32: Notice we used a lambda expression (the functional operation) for the for-each loop
A lamda expression is
This polymorphism:
(1.) Occurs at compile time
(2.) Also referred to as early binding polymorphism because the decision regarding the method to be called
is made at compile time.
(3.) Overloads the method of a class by using the same name but different number and/or parameter types of
that method in a
class in order to perform different tasks. (Method Overloading)
For this to occur, the method in the class must not have the same number and parameter type to perform
those different tasks.
(4.) Overloads the operator of a class to perform different tasks. (Operator Overloading)
Static Polymorphism consists of Method Overloading and Operator Overloading.
As at 03/08/2021, Java does not support Operator Overloading
You may want to read one of Oracle blogs (written in June 8, 2020) regarding Java and operator overloading.
(https://blogs.oracle.com/javamagazine/is-it-time-for-overloading-in-java)
Let us demonstrate Method Overloading in Static Polymorphism.
Let us just focus on Rectangle.
Another property we shall add is that each angle in a Rectangle is a right angle. (an angle of 90 degrees).
We shall overload the methods with different parameter data types: (integer data type to calculate the sum of the
interior angles in a Rectangle; string data type to list the properties of a Rectangle; and two double data types to
calculate the perimeter of a Rectangle).
We can also have a parameterless method to list the properties of a Rectangle rather than using the string data type
as a parameter.
Please review the screenshots and the comments.
Static Polymorphism: Method Overloading
(1.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that demonstrate:
(a.) Inheritance
(b.) Multilevel Inheritance
Cite your source(s) accordingly.
(2.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that demonstrate:
(a.) Dynamic Polymorphism
(b.) Method overloading in Static Polymorphism
Cite your source(s) accordingly.
(3.) Extend my application for the Dynamic Polymorphism example by asking for the user-input.
Because you are extending my application, you may use my code if you wish or you may write your own.
However, your results should be the same as mine. You are welcome to add more functionalities.
The program should ask the user to input those constructor arguments for each quadrilateral.
The user should input the values for each quadrilateral and get the same results.
(4.) Extend my application for the Static Polymorphism example (Method Overloading) by asking for the user-input.
Because you are extending my application, you may use my code if you wish or you may write your own.
However, your results should be the same as mine. You are welcome to add more functionalities.
The program should ask the user to input those function arguments for the rectangle.
The user should input those values for each quadrilateral and get the same results.
Textbook Questions
(5.) Question $6$ on Page $508$
(6.) Question $8$ on Page $508$
(1.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(2.) Other substantive responses.
(1.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Make the fields: first name and the grade of the student to be protected
You are welcome to make other fields public if you wish.
Write a Java program that uses Inheritance to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(2.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Write a Java program that uses Interface to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(3.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Write a Java program that uses Polymorphism (Dynamic and/or Static Polymorphism) to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information in that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
Textbook Questions
(4.) Question 10 on Page 509
(5.) Question 2 on Page 562
(6.) Question 6 on Page 564
(7.) Question 8 on Page 565
(8.) Question 10 on Page 565
(9.) Question 13 on Page 566
(10.)
data structures, linear data structures, non-linear data structures, static data structures, dynamic data structures, array, array list, array list class, linked list, linked list class, stack, queue, tree, graph, list interface, collections,
Students will:
(1.) Discuss ArrayList and ArrayList class.
(2.) Implement the methods of ArrayList class.
(3.) Write a program that uses ArrayList of objects to solve a real-world problem.
(4.) Discuss LinkedList and LinkedList class.
(5.) Implement the methods of LinkedList class.
(6.) Write a program that uses LinkedList of objects to solve a real-world problem.
(1.) Textbook Chapter
(2.) ArrayList class by Oracle
(https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
(3.) Arrays (Java SE 11 & JDK 11) by Oracle
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html)
(4.) Array (Java SE 11 & JDK 11) by Oracle
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/Array.html)
(5.) LinkedList (Java SE 13 & JDK 13) by Oracle
(https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/LinkedList.html)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(6.) Type ArrayList in the search bar and view the results.
Then type ArrayList class in the search bar and view the results.
Then type LinkedList in the search bar and view the results.
Then type LinkedList class in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(7.) Type ArrayList in the search bar and view/read the results.
Then type ArrayList class in the search bar and view/read the results.
Then type LinkedList in the search bar and view/read the results.
Then type LinkedList class in the search bar and view/read the results.
A data structure is a way of collecting, organizing, storing, accessing, and manipulating data for efficient use.
We are not going to go into details. The details are for Computer Science (not Information Technology) majors.
Let us briefly review the data structures in Java.
Then, we shall focus on the ArrayList and the LinkedList.
Linear Data Structures | Non-linear Data Structures | |
---|---|---|
In a linear data structure, all the elements are arranged in a linear (sequential) order. The linear data structure is a single level data structure. |
In a non-linear data structure, all the elements are not arranged in a linear order. The non-linear data structure is a multilevel data structure. Examples are: Graph, Tree |
|
Static Data Structures This is the type of data structure where the size is allocated at compile time. It has a fixed size. Examples are: Array |
Dynamic Data Structures This is the type of data structure where the size is allocated at run time. It has a variable size. Examples are: Array List, Linked List, Stack, Queue |
It is a dynamic data structure that:
(1.) Implements the List interface. It implements all optional list operations and permits all elements including
the null.
(2.) Provides methods to manipulate the size of the array that is used to store the list.
The array list is an unsynchronized class, hence it is not thread-safe.
If you did not understand what I just wrote, no worries.
We shall discuss it when we discuss Multithreading in Module 7
It is declared as:
// Declare an array list of the same data type with a specific size
ArrayList<data type> variable = new ArrayList<>(size);
// Declare an array list of the same data type without a specific size
ArrayList<data type> variable = new ArrayList<>();
OR
List<data type> variable = new ArrayList<>();
// Declare an array list of different data types with a specific size
ArrayList<Object> variable = new ArrayList<>(size);
// Declare an array list of different data types without a specific size
ArrayList<Object> variable = new ArrayList<>();
// Declare an array list of a Class with parametized constructors
ArrayList<Class name> variable = new ArrayList<Class name>();
OR
List<Class name> variable = new ArrayList<Class name>();
We learned Arrays in the Beginning Java course.
We shall discuss the ArrayList and the ArrayList class in this module.
Let us discuss some reasons behind the use of ArrayList.
Array | ArrayList |
---|---|
(1.) Array is a list that contains values of the same data type. | (1.) ArrayList is a list that contains values of the same or different data types. |
(2.) Array stores primitive data types and string data type. | (2.) ArrayList stores both primitive and non-primitive data types. |
(3.) Array has a fixed size. Size must be specified when declared. Size cannot be increased or decreased after declaration. |
(3.) ArrayList has a variable size. Size is not specified when declared. Size can be increased or decreased after declaration. |
The ArrayList class is a class of the java.util package.
Please review the implementation of the ArrayList class methods:
ArrayList class methods by Oracle
(https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
(Scroll down till you see the tab: All Methods) and/or
ArrayList class methods by Tutorialspoint
(https://www.tutorialspoint.com/java/util/java_util_arraylist.htm) and/or
ArrayList class methods by Abhi Android
(https://abhiandroid.com/java/arraylist)
Let us create a class that implements an array list of objects, and use it to solve a real-world problem.
Please review the screenshots and the comments.
As you can see from the codes in the screenshots, we can change the values of any of those ArrayList elements.
Is it not interesting that it took the compiler 0 seconds to build and run this application?
(I.) A Singly Linked List is a dynamic data structure that:
(1.) Contains elements in such a way that each element is linked to it's successor.
The last element is then linked to a null.
The elements are called nodes.
This implies that each node contains a data and a reference to the next node.
The last node contains a data and a link to the null. The last element is the Tail element.
Contains a reference only to the first element in the list. The first element is the Head element.
(2.) Implements the List and Deque interfaces. It implements all optional list operations and permits all elements including
the null.
(3.) Provides methods to manipulate the size of the array that is used to store the list.
The linked list is an unsynchronized class, hence it is not thread-safe.
If you did not understand what I just wrote, no worries.
We shall discuss it when we discuss Multithreading in Module 7
We also have:
(II.) Doubly Linked List: (also known as the Linked List) is a linked list where every node has a link to the previous node and the next node.
In that case, the head element is linked to null and the tail element is also linked to null.
This implies that every node has the data, link to the previous node, and the link to the next node.
(III.) Circular Linked List: is a linked list in which every node is linked to the next node; and there is no null.
It can traverse in the forward or backward direction.
It is similar to the singly linked list except that the last node has a link to the first node.
(IV.) Doubly Circular Linked List: is a linked list in which every node is doubly linked: a link to the previous node
and another link to the next node; there is no null; and it can traverse in the forward or backward direction.
The LinkedList is declared as:
// Declare a linked list of the same data type with a specific size
LinkedList<data type> variable = new LinkedList<>(size);
// Declare a linked list of the same data type without a specific size
LinkedList<data type> variable = new LinkedList<>();
OR
List<data type> variable = new LinkedList<>();
// Declare a linked list of different data types with a specific size
LinkedList<Object> variable = new LinkedList<>(size);
// Declare a linked list of different data types without a specific size
LinkedList<Object> variable = new LinkedList<>();
// Declare a linked list of a Class with parametized constructors
LinkedList<Class name> variable = new LinkedList<Class name>();
OR
List<Class name> variable = new LinkedList<Class name>();
Let us compare and contrast the ArrayList and LinkedList.
ArrayList | LinkedList |
---|---|
(1.) ArrayList uses a dynamic array to store its elements. You can access each element in the list using the index. |
(1.) LinkedList uses the doubly linked list to store its elements. To assess each element, you begin from the head element, then to the next element until you get to the specific element you want. This consumes time. |
Hence, ArrayList is faster in storing and accessing elements. | |
(2.) To add or delete elements, or to change the values of elements in an ArrayList; there is a bit shift in the memory locations of the initial elements. The processing takes time. | (2.) To add or delete elements, or to change the values of elements in a LinkedList; there is no bit shift in the memory. |
Hence, LinkedList is faster in manipulating (add, delete, change values of elements) elements. | |
(3.) ArrayList implements the List interface. | (3.) LinkedList implements both the List interface and the Queue interface. |
(4.) It is best to use an ArrayList when: (a.) one needs to access random elements. (b.) one need to add or remove elements at the end of the list. |
(4.) It is best to use a LinkedList when: (a.) one needs to use the list by looping through it rather than accessing random elements. (b.) one needs to add and remove elements at the beginning, middle, or end of the list. |
The LinkedList class is a class of the java.util package.
Please review the implementation of the LinkedList class methods:
LinkedList class methods by Oracle
(https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/LinkedList.html)
(Scroll down till you see the tab: All Methods) and/or
LinkedList class methods by Tutorialspoint
(https://www.tutorialspoint.com/java/util/java_util_linkedlist.htm) and/or
LinkedList class methods by Abhi Android
(https://abhiandroid.com/java/linkedlist-methods-examples.html)
Let us create a class that implements a linked list of objects, and use it to solve a real-world problem.
Please review the screenshots and the comments.
As you can see from the codes in the screenshots, we can change the values of any of those LinkedList elements.
Is it not interesting that it took the compiler 0 seconds to build and run this application?
If you use Strings:
You may use strings not written in English language. However, if you use any language other than English language,
it is important you translate it. Your colleagues and I need to understand your code.
Insensitive words, or any words deemed inappropriate to any race, gender, religion are unacceptable. Any violation
will not yield any point.
If you are not sure of the words/string to use, please contact me first.
Remember DB 3 Requirement. There are enough methods for everyone. If all the methods are done, please
attempt another question.
Please review the:
ArrayList class methods by Oracle
(https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)
(Scroll down till you see the tab: All Methods) and/or
ArrayList class methods by Tutorialspoint
(https://www.tutorialspoint.com/java/util/java_util_arraylist.htm) and/or
ArrayList class methods by Abhi Android
(https://abhiandroid.com/java/arraylist)
(1.) Review the methods and the examples.
Pick any five methods.
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
Please review the:
LinkedList class methods by Oracle
(https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/LinkedList.html)
(Scroll down till you see the tab: All Methods) and/or
LinkedList class methods by Tutorialspoint
(https://www.tutorialspoint.com/java/util/java_util_linkedlist.htm) and/or
LinkedList class methods by Abhi Android
(https://abhiandroid.com/java/linkedlist-methods-examples.html)
(2.) Review the methods and the examples.
Pick any five methods.
Write the code examples for each method and implement each of them.
Run your codes.
Display the results.
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java Collections: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/collection/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(3.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different method to work on the same object or same data type used by your colleague.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
Textbook Questions
(1.) Question (10.) on Pages 462 and 463
(2.) Question (2.) on Pages 465 and 466
(3.) Please review the example we did for the ArrayList of Objects and the LinkedList of Objects
The objects are the elements of the array list and the linked list respectively.
Hence, it is referred to as ArrayList of Objects and LinkedList of Objects respectively.
Extend the application by adding user-input for each class member of the objects of the array list or the linked list.
The same output should be displayed.
(4.) Grade Point Average (GPA) Calculation for Several Students
Please review Question (7.) on the website: Solved Examples on the Measures of Center
(www.descriptive-statistics.appspot.com/measuresCenter.html)
Review the steps in calculating Rita's GPA.
Use only the five courses listed in the example.
Make the fields: first name and the grade of the student to be protected
You are welcome to make other fields public if you wish.
Write a Java program that uses ArrayList of Objects or LinkedList of Objects to calculate the GPA of Rita and at least one other student simultaneously (at the same time)
Use the same numbers in Question (7.) to calculate Rita's GPA.
For the other student, use a fictitious name or Nameless; and use every grade: $A, B, C, D, F$ in the calculation.
For example: the student should make an $A$ in one course, a $B$ in one course, a $C$ in one course, a $D$ in one course
and an $F$ in one course.
The output of your program should include the information in the table as seen in the solution for Question (7.):
(a.) the name of the student
(b.) the each course and the grade for each course
(c.) the corresponding point for the grades
(d.) the credit hour for each course
(e.) the sum of the credit hours
(f.) the corresponding grade points
(g.) the sum of the grade points
(h.) the GPA
Do you understand the information on that table?
The user (student) should be able to look at your output and understand the GPA calculation very well.
These are the minimum requirements.
You may wish to give recommendation and advice among others to the user/student based on the grade and/or the GPA.
(5.)
create, read, write, append, delete, byte, character, charset, character set, stream, file, text file, binary file, File class, Scanner class, loop, delimiter, regular expression, regex, pattern, Pattern class, FileReader class, BufferedReader class, FileWriter class, BufferedWriter class, FileNotFoundException class, IOException class, java.io.package, java.nio.file package, newBufferedReader, newBufferedWriter, URI, uniform resource identifier, backing store, byte, directory path, disk storage, file name, directory name, file stream, sequential access file, synchronous file operations, random access file processing, text file processing, object-based file processing,
Students will:
(1.) Write programs that reads text from a text file.
(2.) Write programs that writes text to a text file.
(3.) Write programs that appends text to a text file.
(4.) Write programs that reads characters from a string.
(5.) Write programs that writes characters to a string.
(6.) Implement the methods of the File class.
(7.) Implement the methods of the FileReader class.
(8.) Implement the methods of the BufferedReader class.
(9.) Delete files.
(1.) Textbook Chapter
(2.) Streams and Files by Oracle (Review all)
(https://docs.oracle.com/javase/tutorial/essential/io/)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(3.) Type Java Files and Streams in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(4.) Type Java Files and Streams in the search bar and view/read the results.
A file is an ordered and named collection of bytes that has a storage medium.
Working with files implies working with directory paths, disk storage, and file and directory names.
A stream is a sequence of bytes that is used to read from, and write to a storage medium.
Streams involve three fundamental operations.
These operations are:
(1.) Reading: This involves the transfer of data from a stream into a data structure, such as an array of bytes.
(2.) Writing: This involves the transfer of data to a stream from a data source.
(3.) Seeking: This involves the querying and modifying of the current position within a stream.
The storage medium is also known as backing store.
These include disks and memory among others.
File and stream I/O (Input/Output) is the transfer of data to, or from a storage medium.
A text file is a file that contains only text.
It does not contain non-text characters.
It does not contain images.
It has no formatting and no emphasized texts such as underline, bold, italicized, highlighted, colors, etc.
The most common are the files that end with .txt extension.
Main software for text files (text editors) are the Notepad on Windows computers and the TextEdit on Mac computers.
A binary file is a non-text file.
It is constructed from a sequence of 0s and 1s (binary = base two = zero and one only)
It may contain formatted or unformatted data encoded within binary format.
Examples include: media files (video files such as .mp4; audio files such as .mp3; image files such as .png, .jpg,
.gif; formatted document files such as .pdf, .rtf, .doc; executable files such as .exe, .jar; among others)
Sequential access file processing is the ability of the computer to read or write to the file sequentially
(from beginning to end).
These are common with text files.
Compare sequential access file processing with synchronous file operation.
Random access file processing is the ability of the computer to read or write to the file anywhere (at any
position) in the file. These are common with database files.
Be it as it may, the computer can read sequential files randomly, as well as read random files sequentially.
We studied: Strings, Booleans, Date and Time and Arrays in the Beginning Java.
We studied: ArrayList Class and LinkedList Class in the previous module in this Advanced Java.
We have also reviewed several String methods/functions.
We shall use some our prior knowledge from those topics, in this module.
For this module, we are only concerned with synchronous file operations
(read synchronously, write synchronously, append synchronously).
The java.io package provides for system input and output through data streams, serialization and the file
system.
We shall use some classes of this package for file handling.
There are several approaches we can use to read a text file.
Let us discuss some of them.
The Java project is FileHandling
It is inside the NetBeansProjects folder in the Documents folder.
The text file is Module7Notes.txt
In this approach, we shall use:
File class of the java.io package to get the text file to read
Scanner class of the java.util package to read the text file
FileNotFoundException class of the java.io package to handle exceptions/errors
File class
(https://docs.oracle.com/javase/10/docs/api/java/io/File.html)
The File class is an abstract representation of file and directory pathnames.
Scanner class
(https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html)
The Scanner:
(1.) can parse primitive types and strings using regular expressions.
(2.) breaks its input into tokens using a delimiter pattern, which matches whitespace by default.
The resulting tokens may then be converted into values of different types using the various next methods.
(3.) can also use delimiters other than whitespace.(Please see the Second Approach)
FileNotFoundException class
(https://docs.oracle.com/javase/10/docs/api/java/io/FileNotFoundException.html)
The FileNotFoundException class signals that an attempt to open the file denoted by a specified pathname has
failed.
The file: Module7Notes.txt is not in the Project (the default location).
Therefore, the output is:
To read the file, it must be placed directly in the Project: FileHandling
The file is now read:
Student: What if I want to save my file in my preferred location?
Teacher: You can...actually that is my preference as well.
Let us save the file on my OneDrive (in the cloud).
One of the reasons why I prefer saving files in the cloud (OneDrive, Google Drive) is because I can easily make
changes to it.
The location of the file is now: C:\Users\chukw\OneDrive\Documents\AdvancedJava\Module7
The location of the file including the file is:
C:\Users\chukw\OneDrive\Documents\AdvancedJava\Module7\Module7Notes.txt
For Windows users: we include the backslash escape sequence in specifying the file path:
C:\\Users\\chukw\\OneDrive\\Documents\\AdvancedJava\\Module7\\Module7Notes.txt
For Mac and Linux users: we specify the file path as:
C:/Users/chukw/OneDrive/Documents/AdvancedJava/Module7/Module7Notes.txt
Let us discuss more approaches to reading a text file.
We shall specify the "new" file path in the object of the File class.
In this approach, we shall use:
File class of the java.io package to get the text file to read
FileNotFoundException class of the java.io package to handle exceptions/errors
Scanner class of the java.util package to read the text file
A Delimiter is a sequence of one or more characters that separate text strings.
Regular expressions are encoded text strings used as patterns to match, locate, and manage strings.
The Pattern class of the java.util.regex is a compiled representation of a regular expression.
Pattern class
(https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html)
In this approach, we shall use:
FileReader class of the java.io package to read the text file
IOException class of the java.io package to indicate if an I/O (Input/Output) exception occur.
FileReader class
(https://docs.oracle.com/javase/10/docs/api/java/io/FileReader.html)
The FileReader class is a convenience class for reading character files.
It is used for reading streams of characters.
The constructors of this class assume that the default character encoding and the default byte-buffer size are
appropriate.
To specify these values yourself, construct an InputStreamReader on a FileInputStream.
To read streams of raw bytes, use a FileInputStream.
IOException class
(https://docs.oracle.com/javase/10/docs/api/java/io/IOException.html)
The IOException class signals that an I/O exception of some sort has occurred.
It is the general class of exceptions produced by failed or interrupted I/O operations.
Student: Mr. C, you decided to use IOException class rather than the FileNotFoundException class for this
approach.
"Why is that?"...speaking like an American lol
Teacher: The reason is because the FileNotFoundException class extends the IOException class.
This implies that it inherits from the IOException class.
This implies that the IOException class is the super class.
So, it will catch FileNotFoundException exceptions as well as other input/output exceptions.
In this approach, we shall use:
FileReader class of the java.io package to get the text file and read it
BufferedReader class of the java.io package to "actually" read the text file from the object of the FileReader class
IOException class of the java.io package to handle input/output exceptions/errors
BufferedReader class
(https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html)
The BufferedReader reads text from a character-input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
So, we shall create an object of the FileReader class to get the text file to read it
Then, we create an object of the BufferedReader class to "actually" read the text file by reading from the object of
the FileReader class.
This is the preferred approach.
Student: Why is the BufferedReader class approach the preferred approach to reading text files?
Why do we have to use it to read from the FileReader?
Teacher: Very good question.
It's Java...
So, here's the thing: In general, each read request made of a Reader causes a corresponding read request to
be made of the underlying character or byte stream.
It is therefore advisable to wrap the BufferedReader around any Reader whose read() operations may be
costly, such as FileReaders and InputStreamReaders.
For example, in our code:
FileReader userFile = new FileReader("C:\\Users\\chukw\\OneDrive\\Documents\\AdvancedJava\\Module7\\Module7Notes.txt")
readFile = new BufferedReader(userFile);
which can also be written as:
readFile = new BufferedReader(new FileReader("C:\\Users\\chukw\\OneDrive\\Documents\\AdvancedJava\\Module7\\Module7Notes.txt"));
The BufferedReader will buffer the input from the main file: Module7Notes.txt
Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file,
converted into characters, and then returned, which can be very inefficient.
Student: Another question
You mentioned InputStreamReaders...
Any reason why you chose FileReader to InputStreamReader?
Teacher: You can also use
InputStreamReader
(https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/io/InputStreamReader.html)
wrapped within a BufferedReader to read a text file.
However, FileReader reads characters while InputStreamReader reads bytes and decodes them into characters using a
specified charset.
A text file is any file containing only readable characters.
Hence, the FileReader (which reads characters directly) rather than InputStreamReader
(which reads bytes and decodes them into characters) is preferred to be wrapped within a BufferedReader to read a
text file.
This does not mean that you cannot wrap an InputStreamReader within a BufferedReader reader to read a text file.
However, it will take a longer time than using a FileReader with a BufferedReader because it does not read characters
directly.
Let us discuss more file handling operations.
Creating, Writing, and Appending to Files
We can create a new file and write text to it using any of these ways:
(1.) Create the new file and write text to it
OR
(2.) Write text directly to the file. This process creates the new file and then writes to it.
The write operation looks for the file and if it cannot find it, it creates the file and writes text to it.
After writing text to the file, we can append more text (append, not write) to it.
This is because anytime we write text to an existing file, it deletes the existing text and writes the new text.
So: if we want to erase all the content of an existing file, we write to it.
If we want to add to the content of an existing file, we append to it.
If we want to change some of the content of an existing file, we can read the characters,
delete the charcaters, insert characters, and replace characters among others. We shall discuss those operations later.
For now, let us continue our discussion on file operations and then we can discuss character operations later.
Let us create a file, write to it, and read from it.
As with the read operation, there are several approaches to the write operation.
Let us discuss some of these approaches.
In this approach, we shall use:
File class of the java.io package to get the text file to read
FileWriter class of the java.io.package to write to the text file
BufferedWriter class of the java.io.package to "actually" write to the text file from the object of the FileWriter class
FileReader class of the java.io package to get the text file and read it
BufferedReader class of the java.io package to "actually" read the text file from the object of the FileReader class
IOException class of the java.io package to handle input/output exceptions/errors
Let us review the new additions (the ones we did not discuss previously)
FileWriter class
(https://docs.oracle.com/javase/10/docs/api/java/io/FileWriter.html)
The FileWriter is the class for writing character files. It is meant for writing streams of characters.
BufferedWriter class
(https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html)
The BufferedWriter Writes text to a character-output stream, buffering characters so as to provide for the
efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
So, we shall create an object of the FileWriter class to get the text file to write to it
Then, we create an object of the BufferedWriter class to "actually" write to the text file by writing from the object of
the FileWriter class.
Student: Mr. C
Do you realize you did not complete the list in the text file?
Teacher: Nice observation.
Yes, I do
Let us complete it by appending the remaining characteristics to that existing file.
In this approach, we shall use:
FileWriter class of the java.io.package to append to the existing file
BufferedWriter class of the java.io.package to "actually" append to the text file from the object of the FileWriter class
FileReader class of the java.io package to get the text file and read it
BufferedReader class of the java.io package to "actually" read the text file from the object of the FileReader class
IOException class of the java.io package to handle input/output exceptions/errors
One of the constructors of the FileWriter class is: FileWriter(String fileName, boolean append)
It constructs a FileWriter object given a file name with a Boolean indicating whether or not to append the data written.
A Boolean value of true indicates that the data should be appended to the file
A Boolean value of false indicates that the data should not be appended to the file.
Because we want to append the data (remaining characteristics) to the existing file, we shall use the Boolean value of
true
We did not create the file.
But we want to write to it.
This implies that the object will open the file for writing. But because the does not exist, it will create it.
Then, it will write to it.
Then, we create another object that will read from it.
So far, we have been using the java.io package (Java Input/Output package)
But we do have the java.nio.file package (Java New Input/Output file package)
In this approach, we shall use:
(1.) Files class of the java.nio.file package
(https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html)
This class consists exclusively of static methods that operate on files, directories, or other types of files.
It allows us to use the newBufferedWriter and the newBufferedReader
The newBUfferedWriter Opens or creates a file for writing, returning a BufferedWriter to write
text to the file in an efficient manner.
The newBufferedReader Opens a file for reading, returning a BufferedReader to read text from the file in an
efficient manner.
(2.) Paths class of the java.nio.file package
(https://docs.oracle.com/javase/10/docs/api/java/nio/file/Paths.html)
This class consists exclusively of static methods that return a Path by converting a path string or URI (uniform resource identifier).
It enables us to use the Paths class to get the file for writing and reading operations.
(3.) BufferedWriter class of the java.io.package to write to the text file
(4.) BufferedReader class of the java.io package to "read the text file from the text file
(5.) IOException class of the java.io package to handle input/output exceptions/errors
Teacher Let us demonstrate an example.
Student: Which example will you use this time?
Teacher: Guess what I'm thinking?
Student: What?
Teacher: About a mnemonic we learned in Junior Secondary School in Nigeria
Junior Secondary School in Nigeria is equivalent to Middle School in the United States.
Student: What is the mnemonic?
Teacher: The mnemonic that helped us to write the first twenty elements of the Periodic Table?
I even made a YouTube video about it.
Student: Interesting.
Where is the video?
Can you write the elements off hand?
Teacher: Sure 😊
The link is: 1st 20 Elements of the Periodic Table
Let us write the first the mnemonic, the element, and the symbol for the first twenty elements.
Then, read the file.
We shall name the file: Elements.txt and save it in this location:
C:\Users\chukw\OneDrive\Documents\AdvancedJava\Module6\FilesStreams\Elements.txt
But remember we shall add an additional backslash in that path in order to save it in that location.
In the program, we shall use:
C:\\Users\\chukw\\OneDrive\\Documents\\AdvancedJava\\Module6\\FilesStreams\\Elements.txt
Let's do it.
(1.) Use any academic field/discipline/area of your interest.
Find any topic(s) in that discipline that you are knowledgeable about/proficient in.
With clear explanations and comments, write programs that:
(a.) Writes text to a text file
(b.) Appends text to the text file
(c.) Reads from the text file.
Use any approach you prefer.
Cite your source(s) accordingly.
(2.) Please review the fields, constructors, and methods of the:
File class
(https://docs.oracle.com/javase/10/docs/api/java/io/File.html)
Implement any two methods
(3.) Please review the constructors and methods of the:
FileReader class
(https://docs.oracle.com/javase/10/docs/api/java/io/FileReader.html)
Implement any two methods
(4.) Please review the constructors and methods of the:
BufferedReader class
(https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html)
Implement any two methods
Java Programming Exercises, Practice, Solution by W3Resource
Please review:
Java I/O Programming: Exercises, Practice, Solution
(https://www.w3resource.com/java-exercises/io/index.php)
You are provided with the Questions and the Solutions.
No more than one student may do any specific question.
(5.) Write the Question as a comment in your program. Include the Title and the Question Number.
Write clear comments for each line of code in the Solution.
Run the program.
Textbook Questions
(6.) Question (6.) on Page 694
(1.) Review the post (Discuss Questions) done by your colleagues.
Use a different method to work on the same file used by your colleague.
(2.) Review the post (Discuss Questions and Assess Questions) done by your colleagues.
If your colleague developed a console application for a program, develop a desktop application for the same program.
If your colleague developed a desktop application for a program, develop a console application for the same program.
(3.) Other substantive responses.
(1.) Please review the screenshots in Example $6$
Use the same file name.
The same output is required.
The spacing and format of that output is required.
There are two columns after the third line sentence in that output: one column is for the acronym (letters) and the
other column is for the characteristics (words).
Write a file that has only the sentences and the words without the acronym.
Insert each letter of the acronym to the corresponding characteristic (word) in each line.
Include clear explanations as comments in your program regarding the method(s) that you used to do it.
Read the file.
This is a description of the tasks.
1st Step: Create a text file: LivingThings.txt and write these text (without the acronym) to the file:
2nd Step: Insert each acronym in its respective place.
3rd Step: Read the file.
And please do not forget to: Include clear explanations as comments in your program
regarding the method(s) that you used to do it.
(2.) Please review the screenshots in Example $7$
Use the same file name.
The same output is required.
The spacing and format of that output is required.
There are three columns after the first line sentence in the output: the first column is for the Mnemonic,
the second column is for the Element, and the third column is for the Symbol.
Write a file that has only the sentence, the mnemonic, and the elements without the symbols.
Insert each symbol to the corresponding element in each line.
Include clear explanations as comments in your program regarding the method(s) that you used to do it.
Read the file.
This is a description of the tasks.
1st Step: Create a text file: Elements.txt and write the sentence, the mnemonic, and the elements
without the symbols.
2nd Step: Include the word, Symbol; and insert each symbol in its respective place.
3rd Step: Read the file.
And please do not forget to: Include clear explanations as comments in your program
regarding the method(s) that you used to do it.
Textbook Questions
(3.) Question $10.$ on Page $695$
process, thread, execution unit, multithreading,
Students will:
(1.) Discuss Java Threads.
(2.) Discuss Multithreading in Java.
(3.) Implement methods of the Thread class of the java.lang package.
(4.) Solve real-world applications using Java Multithreading.
(1.) Textbook Chapter
(2.) Processes and Threads (The Java Tutorials) by Oracle
(https://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html)
(3.) Thread (Java SE 10 & JDK 10) by Oracle
(https://docs.oracle.com/javase/10/docs/api/java/lang/Thread.html)
(4.) Java.lang.Thread Class by Tutorialspoint
(https://www.tutorialspoint.com/java/lang/java_lang_thread.htm)
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(5.) Type Java Threads in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(6.) Type Java Threads in the search bar and view/read the results.
Let us review the Module7Notes.txt we wrote in the previous module.
(1.) Concurrent Programming is the ability of a program to run several tasks at the same time.
(2.) The Java Programming language is designed to support concurrent programming.
(3.) There are two units of execution in concurrent programming namely: processes and threads.
(4.) A process is a self-contained execution environment.
(5.) It is like a program or an application. However, a program may be a set of cooperating processes.
(6.) A thread is a lightweight independent execution unit.
It exists within a process. This implies that every process has at least one thread.
(7.) Threads share the resources of the process including memory and open files.
(8.) An essential feature of Java programming is Multithreading execution.
(9.) Every Java program has the default main thread that executes the main method (notice the public static void
main(String[] args) method in every Java program).
(10.) That main thread is created by the Java Virtual Machine (JVM) at the start of the program.
(11.) That main thread can create additional threads.
This implies that multiple threads can run concurrently in a Java program.
(12.) The process of executing multiple threads at the same time is known as Multithreading.
For Question (1.):
Please review:
Java.lang.Thread Class by Tutorialspoint
and/or
Thread (Java SE 10 & JDK 10) by Oracle
(1.) Implement any two methods of the Thread class of the java.lang package
At least one of the methods should be different for each student.
(2.)
(3.)
(1.)
(2.)
(3.)
Students will:
(1.) Textbook Chapter
Videos:
Please click the RESOURCES tab of this website
Click the LinkedIn Learning (Kent State University) link
Follow the directions to access the website.
(4.) Type Software Design and/or Software Interface in the search bar and view the results.
Videos and Textbooks:
Please click the RESOURCES tab of this website
Click the O'Reilly Online Learning link
Follow the directions to access the website.
(5.) Type Software Design and/or Software Interface in the search bar and view/read the results.
Each question in this tab is to be done by only one student.
You do not need to respond to the initial post of another student.
(1.)
There are three options for your Final Exam.
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Access the MindTap Course
Course Key: MTPP-BB6Q-1MX1 (Did you notice it three times in this document?)
This exam is designed to assess your understanding of the Java language.
You have reviewed several topics and several concepts in each topic for eight modules.
Pick at least $1$ concept in at least $1$ topic in each of the $8$ modules.
That gives at least $8$ concepts in $8$ different topics in $8$ modules.
Find two more concepts in any topic in any module.
That gives $10$ concepts.
For each concept:
(1.) Write at least three sentences about that concept.
(2.) Develop a program about that concept.
In other words, write at least one code example about the concept.
Run the code.
Display the output.
Submit clear screenshots of your program (code and output)
Deliverables:
(1.) $10$ concepts in $10$ different topics for $8$ modules
Please write the: Module number, the Topic, and the Concept
(2.) Three sentences for each concept.
(3.) Code for each concept.
(4.) Output for each concept.
Please submit all these information as a zipped folder (.zip folder) in the Final Exam folder of the Blackboard course.
This exam is designed to assess your understanding of the Java language.
Please review all the questions and answers of the
Advanced Placement (AP) Computer Science Exams
Student: Mr. C, you are giving us a final exam with the answers?
How nice of you?
Teacher: Yes of course, I am nice. 😊
But, please read on.
Please:
(1.) Review Past Questions and Answers
You may not do any of those questions because they have been done already.
(2.) Do not attempt any question already indicated by your colleague.
If your colleague indicates by writing that he/she is working on a question, then you need to find another question.
No two or more students are permitted to do the same question.
(3.) Pick any five questions.
(4.) Go to the Final Exam Questions forum of the Blackboard course.
(5.) Write the question numbers in that forum only if it has not been written by any other student.
In other words, you need to review any questions posted by your colleagues and make sure that you do not attempt
the same question.
(6.) Explain the solutions of those five questions using your own explanations
and your code examples.
(7.) Number the questions, the solutions, your code examples and output, and your
explanations based on the actual question numbers.
(8.) Submit the actual questions, the corresponding numbered solutions, your
corresponding numbered explanations and your corresponding code examples and output and any other relevant
information in the Final Exam folder of the Blackboard course.
(9.) Make your work easy for me to grade.
In other words, write detailed clear specific explanations.
Do not give me any avenue to deduct points.
For example:
First Task: Notify your colleagues of the questions you intend to do.
In the Final Exam Questions forum of the Blackboard course: you may write:
Hey guys, I am doing $2006$ Question ($2$.), $2010$ Question ($3$.), ... etc.
Second Task: Do the questions.
(1.) $2006$ Question (2.)
Write the question or take screenshots of the question.
Develop the Java program. Write detailed comments.
Run the program.
Submit clear screenshots of the code and results.
(2.) $2010$ Question (3.)
Write the question or take screenshots of the question.
Develop the Java program. Write detailed comments.
Run the program.
Submit clear screenshots of the code and results.
Third Task: Submit all deliverables.
Submit clear screenshots of the: actual questions, the Java program (including comments) of the solutions,
and the results of the five questions in the Final Exam folder of the Blackboard course.
Should you have any questions, please let me know.
Thank you.
There are three options for your Final Project.
Please choose only one option.
This option is based on your textbook (MindTap course).
This implies that it is not free.
However, you have two-weeks free access.
So, it is free if you can complete all the graded assessments in two weeks.
Access the MindTap Course
Course Key: MTPP-BB6Q-1MX1 (Did you notice it three times in this document?)
It is important you communicate with me for approval prior to doing this project.
Because the course deals with only desktop applications and console applications,
(rather than web applications and mobile applications), you may not do any project that requires a web server
such as contact forms and registration forms among others.
The final project is designed to assess problem-solving skills using the knowledge you have acquired in the
course.
In that regard, solving at least a real-world problem using the knowledge gained in the course is expected.
(1.) Think about any of these companies: our Institution: Kent State University; your local campus; your work place; public and
private schools (excluding home schools); organizations, firms, and businesses
(excluding controversial firms and the like).
Any company you choose should have a verifiable website.
The direct link of the company's website is required.
(2.) Identify a problem on the website that you want to solve.
The problem must be solved by programming using the knowledge acquired from any of the course
topics/concepts/description/learning objectives.
Think about your Midterm Project. You solved a problem: calculating bills, federal taxes, etc.
(3.) Develop the computer program to solve the problem.
Test the program to ensure that it works.
Write detailed comments as applicable.
(4.) Prepare a Documentation Manual/Reflection for the project.
Please cite your sources accordingly.
What is the company?
What is their website?
What problem did you identify?
Did you solve the entire problem or part of the problem?
What course topics/concepts/description/learning objectives did you apply in solving the problem?
How did you solve the problem?
Did you encounter any issues while trying to solve the problem?
Are there any limitations to the project?
Are there any recommendations to the company?
Deliverables:
(1.) Program (all files)
(2.) Clear screenshots of your program (code and output)
(3.) Project Reflection/Documentation Manual
Please submit all these information as a zipped folder (.zip folder) in the Final Project folder of the Blackboard course.
The final project is designed to assess your understanding and analysis of data using the knowledge you have
acquired in the course.
Please:
(1.) Visit my website on: Descriptive Statistics
(2.) Review the information for a good understanding of Descriptive Statistics.
It is highly likely that you have a prior knowledge of this topic. Is that right?
(3.) Click the Project link.
(4.) Review the Project Examples. Ensure you follow all the instructions and directions.
(5.) Complete the Final Project for your course.
(6.) Ask questions. I can help.
If you have any issue at any time and you have reviewed the resources I provided and you cannot fix the issue,
please attend the Office Hours/Live Sessions so I can help you.
(7.) Include all these: (documentation of all your Math work and the .exe file) in OneDrive, create a
shareable link, and post the link in the Final Project Drafts forum of the course on Blackboard or send to me via email.
You may also upload them directly if you prefer.
I shall review and provide feedback.
(8.) Make sure your executable file runs by itself outside the project folder
If it does run, include these three items: single executable file (that runs by itself outside the folder), the
Math documentation (Word document that has the Math part), and the entire project folder, into a folder,
zip the folder (.zip extension only) and submit it in the appropriate area of the Blackboard course.
If it does not run, please fix it.
If you cannot fix it, please attend the Office Hours/Live Sessions so I can help you.
NOTE: Any actual project submitted to me via email will not be graded.
Dear Students,
Greetings to you.
As you evaluate me and my teaching style on the Blackboard course, I ask that you consider these questions
in addition to the survey questions.
Thank you for giving me the opportunity to teach the course.
It was nice working with you.
I wish you the best in your academic profession.
Thank you!
Samuel Dominic Chukwuemeka (SamDom For Peace)
B.Eng., A.A.T, M.Ed., M.S
Working together for success
Grading Method: Grading Method
Classroom/Learning Environment: Blackboard course management system.
Course Assessments: Discussion Board (DB) assignments, Midterm Project, Final Project and the Final Exam
Direct forms of communication: live office hours/tutoring sessions, emails, comments to your DB posts and responses and
phone calls.
Indirect forms of communication: course announcements, websites (notes, videos, etc).
Course Contents
Please review the Course Description and Student Learning Outcomes
It is the first link in your course.
Those are the basic topics that KSU require that I teach.
(1.) Did I cover those topics: teaching and/or providing resources for those topics?
(2.) Did I cover other necessary topics that is relevant for you to succeed in your profession?
(3.) Did the assessments demonstrate the application of the topics?
(4.) Did the contents and assessments demonstrate important skills such as critical thinking, use of technology,
creativity, and organization among others?
Teaching and Learning
(5.) Did you acquire any knowledge from me?
(6.) Did you acquire sufficient knowledge, or more than sufficient knowledge from me?
(7.) Did you acquire any knowledge from any of your colleagues because of how the course was set up?
(8.) Did you acquire sufficient knowledge, or more than sufficient knowledge from any of your colleagues because of
the way the course was set up?
(9.) Did I provide multiple ways of completing each assessment?
In other words, were you given several options of completing each assessment?
(10.) Did I provide effective feedback for any of your assessments?
(11.) Did you acquire any knowledge based on that feedback?
(12.) Did the feedback help you improve in any way?
(13.) Did you have enough support to ensure the successful completion of the course?
Were your questions answered?
Did you have enough resources/learning aids?
(14.) Did I provide a safe and conducive environment for learning?
(15.) Was the Grading Method fair?
Pacing Guide
(16.) Were you given enough time to learn the contents?
(17.) Were you given enough time to complete the assessments?
Consider the fact that you were given two due dates for your Midterm Project, Final Project, and Final Exam; and that there
was no penalty for late work after the first due date.
Professionalism
(18.) In all our communication (both direct and indirect), did I act professionally?
(19.) In all our communication (both direct and indirect), did I use a respectful tone?
(20.) What do you like or dislike about our communication?
Personality
(21.) Based on your experience with me (taking the course with me and communicating with me among others), how
would you describe my person?
Do I give a lot of work?
Do I give a lot of explanations?
Do I have a lot of expectations for my students?
Do I really want you to learn?
Do I really want you to succeed?
Do I ask a lot of questions?
Do I answer questions with questions sometimes?
In those times, please note that it is a teaching technique.
It is never meant to disrespect you. I do not disrespect my students. I respect them.
It is a technique to guide you to review directions/concepts, and explain what you do not understand.
Would you take another course with me? Why or why not?
Did your views/perception about me affect you in completing this course successfully or unsuccessfully?
Need a programmer for personal/professional/commercial projects?
Look no further. Any of my available students (not just the ones listed here) can help.
Just head on to the Division of Student Affairs, Kent State University
or contact me here or via my school email address.
These are nice projects done by my students.
Some of them are Midterm Projects while some are Final Projects.
Because of FERPA (Federal Educational Rights and Privacy Act) laws, only the first names of my students are
written.
NOTE: Java must be installed on your computer for these applications to run.
To run the Console applications, please review the screenshots.
To run the Desktop applications, please double-click the application.
Directions to Run:
Summer (June-Sept) Base Charge: $14.50 First 1000 kWH: $0.100511 Over 1000 kWH: $0.10304Alabama Power increased their rates
(1.) Georgia Public Service Commission: Winter Rate (October - May)
by Rachel
As at today: 04/20/2021, the verifiable website for this application is:
Georgia Power Bill Calculator: Winter Rate (October - May)
(http://www.psc.state.ga.us/calc/electric/GPcalc.asp)
(2.)
Alabama Power: Standard Rate Plan — Family Dwelling : Monthly Rate Schedule : Winter (Oct - May)
by Serina
As at today: 12/24/2021, the verifiable website for this application is:
Standard Rate Plan — Family Dwelling | Alabama Power
(https://www.alabamapower.com/residential/residential-pricing-and-rate-plans/standard-rate-plan-family-dwelling.html)
(3.)
Alabama Power: Standard Rate Plan - Family Dwelling : Summer (June - Sept)
by Cody
As at today: 03/21/2021, the verifiable website for this application is:
Residential Pricing - Standard Family Dwelling Rate | Alabama Power
(https://www.alabamapower.com/residential/residential-pricing-and-rates/standard-family-dwelling-rate.html)
The calculator is based on old rates:
Winter (Oct-May) Base Charge: $14.50 First 750 kWH: $0.100511 Over 750 kWH: $0.088511Alabama Power increased their rates
(1.)
Alabama Power: Standard Rate Plan - Family Dwelling : Summer (June - Sept.)
by Linda
As at today: 03/21/2021, the verifiable website for this application is:
Residential Pricing - Standard Family Dwelling Rate | Alabama Power
(https://www.alabamapower.com/residential/residential-pricing-and-rates/standard-family-dwelling-rate.html)
The calculator is based on old rates:
Winter (Oct-May) Base Charge: $14.50 First 750 kWH: $0.100511 Over 750 kWH: $0.088511Alabama Power increased their rates
Java Tutorials by Oracle (Free)
Java Tutorial: W3schools.com (Free)
Java Documentation: Oracle (Free)
AP Computer Science Java Quick Reference
Java SE Developer Community
American Standard
Code for Information Exchange (ASCII) Characters
Sorting
Techniques and Algorithms
LinkedIn Learning (Kent State University)
O'Reilly Online Learning
For Kent State University students, Select your Institution > Choose “Not Listed?
Click here.”
Enter your Kent State University email address and click Let’s Go
Tutorials, Exercises, and Solutions from W3Resource (Free)
Java Programming Exercises and Solutions from W3Resource (Free)
SoloLearn (Free)
Java for Programmers: Udacity (Free)
Java Notes for Professionals: Stack Overflow Documentation (Free)
Wikibooks: Java Programming (Free)
Stack Overflow: Question and Answer Forum for Computer Science
Lynda.com from LinkedIn Learning (Start for Free. Then, not free)
Codecademy (Start for Free. Then, not free)
Chukwuemeka, S.D (2016, April 30). Samuel Chukwuemeka Tutorials - Math, Science, and
Technology.
Retrieved from https://www.samuelchukwuemeka.com
Farrell, J. (2019). Java Programming. Cengage Learning.
Java Documentation. (n.d.). Oracle Help Center. https://docs.oracle.com/en/java/
Java Notes for Professionals Book. (n.d.). Books.Goalkicker.Com. Retrieved June 30, 2020, from
https://books.goalkicker.com/JavaBook/
AP Computer Science A Past Exam Questions. (2019, May 4). AP Central. https://apcentral.collegeboard.org/courses/ap-computer-science-a/exam/past-exam-questions