Reading from the Text
You should be able to begin reading the text from the beginning; the authors have a clear presentation. Here are specific references to material
covered in this lecture. Realize this is an overview of what we will be doing, so the section mentioned will be from various chapters and may refer to material we haven't covered
yet (or at least not in detail).
Chapter 1
- You should be able to read this whole chapter; we have not covered section 1.7.
Chapter 2
- Read chapter 2; skip sections 2.6 and 2.7 for now.
- We haven't covered assignment, but you should still be able to understand secton 2.2
Chapter 3
- You can try reading sections 3.1 through 3.3; they discuss the concepts behionds
System.out.println
and Scanner
; we will be going into detail
about all this in the next lecture or so.
- You can also read section 3.4
Chapter 5
- Try skimming sections 5.1 and 5.2; it uses an arithmetic operator we haven't introduced yet, but you might be able to understand the basic presentation
Some Motivation
How Would You Walk From Brooklyn College To Newkirk Plaza?
Here's an answer
How Do You Make A Peanut Butter and Jelly Sandwich?
Here's an answer
How Do You Multiply Two 3-digit Numbers?
Here's an answer
Some terms and concepts that are related to the above discussions:
- statement of the task to be performed
- tasks and subtasks
- step-by-step
- precision
- algorithm
- parameters
- actions
- decisions
- repetition
What is Programming?
- computer: a machine capable of carrying out a sequence of operations (typically arithmetic and logical)
- arithmetic and logical because that was the motivation for calculations: census tables, ballistic trajectory tables for canon,
nuclear reaction calculations, etc
- As it turns out ALL computer-based calculations (including sound, image, video, etc) reduce to arithmetic and logical operations
- The original use of the word computers was for humans … Computer (Occupation
- programming: the act of specifying a sequence of actions/commands to be carried out/executed by a computer
- program: a sequence of such commands
- A program is also sometimes known as an app
- programmer: a person trained in the field of programming
An Overview of the Programming Process
We will see there are three basic types of operations required to carry out any task:
- Actions (imperatives)
- Decisions (conditionals)
- Repetition (iteration)
A decent (though not perfect) analogy of the programming process is creating and then carrying out a recipe
- In both cases one is attempting to accomplish something
- The process involves carrying out a sequence of steps
- Each step involves one or more of the above three categories
- The steps must be precisely specified and ordered
A Basic Overview of Recipes and Programs
Recipes Structure
Imagine buying a recipe box with blank recipe cards:
- Every recipe has this same basic wording and layout.
- The recipe is then filled in in the appropriate places
- In particular, 'Recipe Title' would be replaced with the actual name of the recipe
- Notice we present 'Recipe Title' in italics to emphasize its 'placeholder' aspect
(Java) Program Structure
Java programs also have a basic common structure; every program will have a similar layout and common text:
1. public class <ClassName> {
2. public static void main(String [] args) {
3. …
4. }
5. …
6. }
- ClassName is a description (like 'Recipe Title' above) in that it
describes what goes in that location (rather than being the actual text that will go into that location.
- For the program, it would be a name describing what the program does.
- Whenever we have a descriptive name that is to be replaced with some specific text, we will make it italic
(as we did with 'Recipe Title') and enclose it in <>'s.
- We will learn a bit more about the notion of a 'class'; 3115 is where you learn about it in detail
- We will also learn more about the actual meaning of this common structure
- The …'s represent locations in the program where we will put our sequence of operations
- Initially, we will place instructions only at the location of the first …;
eventually we will use the second location as well.
- The rest of the text is always present in exactly that form (at least for our programs in 1115); we call such fixed text
boilerplate
- The line public class <ClassName> {
is known as a class header and the code between the method header and the corresponding closing }
(on line 4) is called a class
- The line public static void main(String [] args) {
is known as a method header, and the code between the method header and the corresponding closing }
(on line 6) is called a method
- We'll have more to say about these two down below and in subsequent lectures
A Trivial Recipe: Cereal & Milk
- We've provided a name for the recipe ('Cereal & Milk'), and filled in the ingredients and instructions
- Not much to this recipe, just a couple of actions
A Trivial Zero'th Program
We provide an equally simple first program, adding no code; all that needs to be added is the name:
Write a program that does nothing except contain the required boilderplate; i.e., the empty program
public class EmptyApp {
public static void main(String [] args) {
}
}
- This program does absolutely nothing — there is no output
- we've included it simply to show the minimal working program, and to show how to provide the program (application) name
- In this case the name is (appropriately) EmptyApp
- In general, the above is how we will present programs in these notes:
- Instructions
- the code
- optional input to the program
- the output
- various explanatory notes
A Somewhat Better First Program
Write a program that displays the text Hello world on the screen.
- We will be providing instructions for our programs
- The instructions will always need to be quite precise
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello world");
}
}
Hello world
- The statement
System.out.println("Hello world");
causes the text Hello world
to be displayed on the screen
- We will have more to say about
System.out.println
after our introduction
- Statement are the actions of the program; again, we will have more to say about them later.
- We named our program
HelloWorld
because that is what it does … prints "Hello world" to the screen.
A More Substantive (but still simple) Recipe: Fried Eggs
Fried Eggs
Here is a recipe with a little more substance:
Ingredients
- 1 tablespoon extra-virgin olive oil
- 1 egg
Instructions
- Crack an egg into a small bowl and place it near the stove.
- Warm your skillet over medium-high heat until it's hot enough that a drop of water sizzles rapidly on contact.
- Reduce the heat to medium and add the olive oil to the pan.
- Gently tilt the pan around so the olive oil covers the base of the pan. The olive oil should be so warm that it shimmers on the pan (if not, give it a little more time to warm up).
- Carefully pour the egg into the skillet.
- Let the egg cook, gently tilting the pan occasionally to redistribute the oil, until the edges are crisp and golden and the yolk is cooked to your liking.
- Transfer the cooked egg to a plate.
Looking a bit more carefully at this we see the three basic categories of operations introduced above:
- (Simple) Actions, such as cracking an egg into a bowl, or tilting the pan
- Decisions, such as warming the skillet to the desired temperature, or cooking the egg until the edges are crisp
- Repetition, such as tilting the pan occasionally to redistribute the oil, or adding drops of water repeatedly until
the pan is hot enough
P01.3 — A More Substantive Program
With regard to programs, we are going to proceed more slowly: we will introduce each of the above categories individually, in programs of increasing
functionality.
- We will use grading as a unifying theme for the programs.
Write a program that calculates the average of a midterm grade of 78 and a final exam grade of 86.
public class ExamAverager {
public static void main(String [] args) {
System.out.println((78+86)/2);
}
}
82
- operators — such as
+
(addition) and /
(division)
are symbols that accept operands (values), and produce a result (the sum for addition,
and the quotient for division).
- The four basic arithmetic operators are
+, -, *, /
- As these operators accept 2 operands, the are callled binary operators
- Note the use of parens (
()
's);
- the usual rules of precedence apply (
*, /
before +, -
)
- parentheses for overriding.
- Unlike our recipe this program does not contain any decisions or repetition, only actions (the arithmetic calculation).
P01.4 — Making the Output More Readable
We'd like to add some descriptive text to out output to let the user know what they're looking at:
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss and prints out
the result together with some descriptive text.
public class ExamAverager {
public static void main(String [] args) {
System.out.println("Gerald Weiss received an 88 and a 92 for an average of " + (88 + 92) / 2);
}
}
Gerald Weiss received an 88 and a 92 for an average of 90
All we've done here is add some descriptive text to the println
When at least one of the operands of +
is a String, the operator
is called the concatenation operator.
The action of the concatentation operator is to textually join the first and second operands
- For example,
"Hello " + "world"
results in "Hello world"
(notice the trailing blank at the end of the string "Hello ".
- If one of the operands is a string and the other is something else (right now, the only other thing we have is a number), the
number is treated as text, and concatenated to the string. Some examples:
"The number is " + 15
produces "The number is 15"
"The average is " + (2+4)/2
produces "The average is 3"
"The sum is " + 2 + 4
produces "The sum is 24"
?!
- This last example shows us we need to be careful about using parentheses when concatenating
P01.5 — Adding a Decision (Conditional)
Let's add an example of the second category of operations: decision-making.
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss, and prints
whether the student has passed or failed the course based on a passing grade of 60.
public class ExamAverager {
public static void main(String [] args) {
System.out.println("Gerald Weiss received an 88 and a 92 for an average of " + (88 + 92) / 2);
if ((88 + 92) / 2 >= 60)
System.out.println("Gerald Weiss passes");
else
System.out.println("Gerald Weiss fails");
}
}
- A conditional is introduced with the word
if
- We will have more to say later on about words in Java with special meaning
- The
if
is followed by a condition — an expression that evaluates to true or false
- In our example it is the expression
(88 + 922 / 2 >= 60)
- The condition of the conditional is always enclosed in parens (
()
's)
- The condition typically contains an equality or relational
operator
- The equality operators are :
==
and !=
- The relational operators are:
<=
,>=
,
<
, >
- For most practical purposes we think of equality and relational operators in the same way, i.e. an operator that
results in a true/false)
Gerald Weiss received an 88 and a 92 for an average of 90
Gerald Weiss passes
Introducing Variables and Types
In the above code, all the values are
hardcoded they appear constantly wherever they are used. There are several issues with
this approach, all of which lead to the introduction of the same concept.
Avoiding Redundant or Repetitious Values
- The above program repeated the student's name, as well as the values of the exams.
- Making a typo would result in us using one value in one place and a different one elsewhere
- For example, misspelling 'Gerald' in one of the prints, or typing '80' in one place
and '88' in another would produce inconsistent and thus incorrect output.
- Similarly, we wrote the expression for the average twice, again inviting the possibility of
making a mistake with one of them, producing inconsistent and incorrect results.
Allowing Different Names and Exam Values
The above program only provides information for a student named Gerald Weiss who received exam grades of 88 and 92.
- We typically want to be able to perform the above calculations on different exam grades as well as other-named
students.
- The conditional is almost silly if it is only applied to the grade of 90; in that situation, it will never
print 'fails'.
We might simply want to be able to quickly change the name of grades and run the program again.
- More importantly though, we might want to run this program once on many successive names and grades
- We can't do this if a specific name and set of grades is specified.
Making the Code More Readable
Looking at the original (88 + 92) / 2 program, it takes a bit of imagination to first realize that an average is being
taken and then even more so that it is the average of two exam grades. We would like that to be clearer.
- Associated with this is the notion of avoiding putting 'magic numbers' into our code, i.e., numbers
that seem to come from nowhere. We will have more to say about this later, when we discuss proper
program design and style.
P01.6 — The Exam Averager Program Using Variables, Types, and Declarations
Write a program that calculates the average of a midterm grade of 88 and a final exam grade of 92 for the student Gerald Weiss,
and prints whether the student has passed or failed the course based on a passing grade of 60.
public class ExamAverager {
public static void main(String [] args) {
String name = "Gerald Weiss";
int midterm = 88;
int finalExam = 92;
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
Gerald Weiss received an 88 and a 92 for an average of 90
Gerald Weiss passes
- We replace the hardcoded values
Gerald Weiss
, 88
, 92
,
with placeholders known as variables
- This allows us to easily change the name and exam grades
- It also allows us to code the calculation of the average only once
- Variables are locations in the computer's memory that can hold values
- Variables are restricted as to the sort of values they can hold; e.g., strings or numbers
- This category of value the variable can hold is called the type of the variable
- We have encountered two types so far:
int
for variables holding integers (numbers)
String
for variables holding text (strings)
- Java requires that one declare, i.e., state one's intention to use, any variables used in the program
- The declaration includes the name of the variable preceded by is type
- for example, in the above code:
String name
and int midterm
- A declaration of a variable can also include an initialization, i.e., and initial value for the variable
- We will discuss variables, types, declarations, and initializations in more detail after this introductory lecture
Introducing variables addresses and resolves the issues presented at the beginning of this section:
- Storing the 'arbitrary' value in a variable allows one to retrieve it by name rather than having to repeatedly code the value
- Using a variable which can contain different values (at different times) allows one to perform the same calculations (e.g. computing an average)
on different values
- Using variables with intuitive names makes the code more understandable
Making Use of the 'Variable' In Variable
- We can now use variables to apply our logic to different values; the question remains however as to populate the variables with those values.
- Even with variables and initialization, the programs — as currently written — have the values hardcoded into the code
- While its true the values appear in the initialization of variables, it is still the case that to change the value requires editing and recompiling the program
- We need some way of providing different sets of values without having to constantly be changing our code
- We do this by having the user supply data from the keyboard
Reading Values (Input) From the Keyboard
- One would guess that if there is a
System.out.println
to print things out, there should also be a System.in.readln
(or something like that) to
read things in.
- It's close but not quite … a bit more work need to be done to read in values from the keyboard.
- For the moment, we will simply present the code as boilerplate again, but we will explain it in a bit
import java.util.Scanner;
public class <ClassName> {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
…
String name = scanner.next(); // next reads in text (until the next blank or 'return' key) typed at the keyboard
int midterm = scanner.nextInt(); // nextInt reads in an integer typed at the keyboard
…
}
}
User Prompts
next
and nextInt
simply wait for the user to enter a value (and press the 'return' (↵) key)
- Without anything further, the user would:
- be presented with a blinking cursor, but no other inidicatio the system is waiting and thus …
- … would not realize the system is expecting them to input anything
- even if they realized the system is waiting, they would have no idea WHAT they are supposed to input (i.,e., a name?, an exam grade?, which exam?)
- To solve this problem, we introduce the notion of a user prompt, i.e., a message displayed to the screen telling (prompting)
the user the both input is expected and furthermore, what sort of input.
- For example, if we wish the user to type in a name, we would code:
System.out.print("Name? ");
String name = scanner.next();
- The
print
vs println
: the ln
stands for line and indicates the
cursor should move to the beginning of the next line after the print; leaving it out causes the cursor to remain where it is
(after the last character displayed).
- We do this so the user's input is on the same line as the prompt (that's why there is a blank space after the
?
of the prompt).
This is so we save vertical real estate; some programming conventions don't care and have the user's
input be on the next line.
- When looking at the program output, one therefore sees the prompts as well as the actual output; while they are both produced by
System.out.print**
's,
we usually distinguish between prompts and the actual output (i.,e., the results calculated by the program logic).
- We will discuss during the lab how to read program output containing prompts when it appears in CodeLab's Output Comparsion window
Notice that no new Java was introduced to solve this problem, merely understanding the issue and applying a clever / common-sense approach. We'll call such an approach
a
technique; we will encounter many such techniques over the course of the semester.
P01.7 — The Exam Grader With Input From the Keyboard
We can now present a program that prompts the user and accepts data typed in from the keyboard.
Modify P01.6 so the data is read from the keyboard.
import java.util.Scanner;
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
Weiss
88
92
Name? Midterm? Final? Weiss received an 88 and a 92 for an average of 90
Weiss passes
- We include all the input-related boilerplate discussed in the previous subsection, the
import
, and declaration of scanner
- Up until now, the program's values were all self-contained as hardcoded values within the program. Now, however, they are read in from the keyboard
when the program is run (i.e., they are not know prior to actually running the program and getting the values).
- It is now necessary, when showing the program's execution output, we first have to show the values input at the keyboard; as the output
depends on those values.
- Notice the change from
Gerald Weiss
to Weiss
. This because next
only reads until the next blank space. Were we to type in
Gerald Weiss
and then hit return (the data is not sent to the machine from the keyboard until you press return), next
would only
read Gerald
and stop at the blank.
The Interactive Session
The above
Input
and
Output
showed exactly what is typed in at the keyboard and printed out by the
System.out.println
's
(and
System.out.print
's) of the program. However, since what is typed at the keyboard is echoed on the screen, what you see displayed looks somewhat different
than the above output:
Here is a sample execution of the program.
User input is in bold. Your program should replicate the prompts and output:
Name? Weiss
Midterm? 88
Final? 92
Weiss received an 88 and a 92 for an average of 90
Weiss passes
- This difference is important for you to understand because CodeLab matches only and exactly your
System.out
output.
- The exercise instructions on the lab web pages show you this interactive session, i.e., the display you actually see: output and echoed input merged together.
- CodeLab display the interactive output as well, but you can also select to see either the input alone, or the output alone
Adding Repetition
- Now that we have variables that can hold different values, and are able to populate them using input from the keyboard (rather than hardcoded values), we
can now introduce the facility to repeat our logic on different values and apply our grading logic to each set of data input
Repeating Sections of Code — the for
Loop
P01.8 — The Grading Program for Three Students
We can now present a program that repeats our grading logic for several students. A
for
loop will provide the repetition and we will use a
Scanner
to read the sets of data from the keyboard.
Modify P01.7 so it processes three students before terminating.
import java.util.Scanner;
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 3; i = i + 1) {
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
}
- We use a 3-repetition
for
loop to read in three sets of student data
- The loop body consists of our (by now familiar) grading logic; supplemented with prompts and keyboard input logic
- Something important to notice: we are reusing our variables each time through the loop
- When we are finished with our processing of an individual student, and have printed out the results
for that student, we no longer need the values contained in the variables, and can reuse them for the next
time around
Weiss
88
92
Arnow
75
95
Cox
80
100
Name?
Midterm?
Final?
Weiss received an 88 and a 92 for an average of 90
Weiss passes
Name?
Midterm?
Final?
Arnow received an 75 and a 95 for an average of 85
Arnow passes
Name?
Midterm?
Final?
Cox received an 80 and a 100 for an average of 90
Cox passes
P01.9 — The Grading Program: Letting the User Decide How Many Students to Process
- The above
for
loop program finally illustrates the power of the computer, with a trivial modification we can have the program perform the grading computation for one million
students.
- However, a similar problem arises to the one that motivated us to introduce variables: regardless of three, ten, or a million students, our program is again limited; this time to the
number of students processed.
- A better approach would be to allow the user to tell us in advance how many students they want to process.
- We will do this by prompting the user to enter how many students and then using that value as the terminating value of our for loop.
- The logic of the loop body does not change whatsoever
Modify P01.8 so that the user is prompted for the number of students to process.
public class ExamAverager {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many students do you wish to process? ");
int howMany = scanner.nextInt();
for (int i = 1; i <= howMany; i = i + 1) {
System.out.print("Name? ");
String name = scanner.next();
System.out.print("Midterm? ");
int midterm = scanner.nextInt();
System.out.print("Final? ");
int finalExam = scanner.nextInt();
int average = (midterm + finalExam) / 2;
System.out.println(name + " received an " + midterm + " and a " + finalExam + " for an average of " + average);
if (average >= 60)
System.out.println(name + " passes");
else
System.out.println(name + " fails");
}
}
}
3
Weiss
88
92
Arnow
75
95
Cox
80
100
How many students do you wish to process?
Name?
Midterm?
Final?
Weiss received an 88 and a 92 for an average of 90
Weiss passes
Name?
Midterm?
Final?
Arnow received an 75 and a 95 for an average of 85
Arnow passes
Name?
Midterm?
Final?
Cox received an 80 and a 100 for an average of 90
Cox passes
- As with prompts, this did not require any new language features, but rather another technique using
language facilities we already knew
- It is often recognizing the application of an existing technique, or coming up with a new one, that
is the most challenging thing about programming
Summary
The above examples illustrated all three fundamental coding tools: actions, decisions, and repetition. We will now return
to each of them in much greater detail.
The Next Level: Organization and Responsibility
- We've just illustrated the operations necessary for any task: basic actions, decisions, and repetition.
- While anything that can be written using a computer can be achieved using those three relatively simple
categories, additional work needs to be done to be able to deal with tasks involving a large number of
operations, many of them quite complex in and of themselves.
Let's revisit the recipe world for a moment and look at a more complex egg recipe:
A More Complex Recipe: Huevos Rancheros
Ingredients
- 1 tablespoon olive oil, divided
- 2 cups salsa (see recipe below)
- 16-ounce can Bush's Cocina Latina Frijoles Negros Machacados
- 4 round corn tortillas
- 1 tablespoon butter
- 4 large eggs
- 1/2 cup crumbled cotija (or feta) cheese, or shredded monterey jack
Instructions
- Heat a skillet over medium heat; add 1 tablespoon of olive oil. When olive oil ripples, add salsa and cook over medium heat, stirring occasionally for about 10 minutes.
- Meanwhile, begin warming beans in a separate pan.
- Transfer cooked salsa to bowl; cover to keep warm.
- Wipe out skillet; heat skillet over medium heat. Add tortillas in single layer to dry skillet (working in batches as needed), cook until warm and slightly toasted, turning as needed. Remove and cover to keep warm.
- Heat skillet over medium heat. Coat pan with a bit of butter. Fry eggs to preference; season to taste with salt and pepper. Add additional butter as needed.
- Serve fried eggs on warm tortillas, topped with cooked salsa, warmed black beans, and cheese. Add any optional chopped fresh cilantro, sliced/diced avocado or avocado, sliced jalapeno or fresh corn as desired.
Salsa
…
a salsa recipe would go here
…
- There are two things happening here:
- There is a subtask you are asked to perform (the salsa)
- There is something else here that you are asked to get from elsewhere (the Bush's beans) either
because you don't have the time or knowledge to prepare them yourself, or because they are better than
what you could prepare.
- Conceivably, if this is an extremely complicated recipe (for example some sort of fancy cake), the recipe might suggest
you ask someone with experience in cake decoration to do the final frosting
- Basically, this all boils down to controlling the complexity of the recipe: break it into subtasks and use outside resources
when necessary, possible, and/or desirable.
Methods and Classes
Similarly with software development; which is typically much more complicated than most recipes. To control
such complexity we will organize our code into various levels.
Methods
Methods are logical units of code that represent subtasks.
- just as the salsa was a self-contained 'subrecipe', we will design our methods to be
logically self-contained, in the sense of accomplishing a specific, well-defined subtak
We will cover methods shortly; deciding what should be turned into a method, and then designing the method proper takes
practice.
Classes
Classes are just collections of resources — methods and data (variables).
- The code we have been writing is part of a class
- we also can use outside resources, i.e., code written outside of the code we are currently working on
- We might use these resources (to refer back to our recipe analogy) either because
- it's quicker to do so
- we don't know how to code the necessary task
- they might simply do a better job than we could
- these classes may be
- supplied by Java
- written by a third-party
- written by us
Deciding what should be a class and how to design it — as with methods — requires practice (even more so);
and this is deferred to the next course in the sequence.
- We will however be using classes to some extent in our work.
- Two examples are the classes
System
and Scanner
- As we said above, although we're treating them in this introductory lecture as boilerplate,
more detailed explanations will be forthcoming.
But, remember, at the end of the day, all that is needed to accomplish any programmable task are actions, decisions, and repetition;
methods and classes are 'merely' organizational elements.
One Last Thing to Think About
- Consider the effect of
scanner.next
:
- it reads characters typed in from the keyboard
- it stops when a blank is encountered
- The first of these is a repetition, the second a decision; yet we think of
next
as a 'simple', 'basic' action.
- This is similar to the recipe action 'stir the pot'; while this is indeed an action, it contains within it a repetition
- Similarly, "preheat oven to 350 degrees" contains a decision
- Other examples:
- Adding numbers; e.g.
135 + 457
; the machine performs the operation in a manner similar to what we do, i.e., summing each pair of digits and
dealing with carry — a repetition of simple, single-digit additions to achieve full addition
println
need to display each individual character on the screen; it does this by repeating the action of displaying a single character for each
character in the text it is displaying
- The basic idea is that actions are themselves tasks composed of the operations of simpler actions, decisions, and repetition
- Where does this stop? … one could think when one reaches the hardware of the machine; but even then one could then think of
the electrical circuits, the electrons flowing in the wires, etc
- In practice, we stop when we have an action that suits us …
println
does what we need; it might be interesting to
look into it to see how it works, but not necessary
… and All the Way Up
- The same idea works in the other direction: sequences of action, decision, and repetition operations combine to form
new actions
- In the recipe world, combining the recipes of salsa fried eggs, and mashed black beans forms the huevos rancheros
recipe.
- In our grading example, calculation of the average could be thought of as an 'averaging' action, while the
decision logic could be thought of as forming a pass/fail test action
- In fact, that's exactly the idea behind a method, i.w., a sequence of operations (code) that are form a cohesive logical
unit.
- … And collections of methods and other stuff) are then grouped together to form classes.
Where Do We Go From Here?
- As mentioned, the three basic operations: actions, decisions, and repetition form the foundation of performing any task;
whether done by a human or computer.
- This introductory lecture has illustrated each of those categories.
- We've also introduced the notions of methods and classes
- There is much more work to do though, in order to master programming:
- In addition to the basic boilerplate presented in the empty app, quite a bit of other code has been handed to you as
boilerplate as well (e.g.
System.out.print
, Scanner scanner = new Scannner(System.in)
);
we need to explain and explore these in more detail
- We need to investigate expressions in more detail; arithmetic as well as logical expressions —
expressions that form the basis of conditions
- the decisions in our sample programs above were trivial; real problems typically require conditions of far greater complexity;
we need to get comfortable with these as well, learn how to manipulate and evaluate them
- Similarly, although the
for
loop provides a powerful mechanism for repetition, it is nowhere sufficient
to address many situations; loops will form a major part of our curriculum.
- As the programs get more complex, we need to get a handle on how to test them to make sure they do what they are supposed to
be doing
- While looping allows us to repeatedly execute the same logic on different data, we need some way of supplying and
working with that data; typing millions of values in from the keyboard is clearly not a efficient, productive, nor
reasonable approach. We need to learn how to work with files on disk, as well as large amounts of data in memory.
- And all along, we need to learn how to think clearly, precisely and algorithmically, i.e., learn how to
provide step-by-step solutions to our programming tasks.