Action: prints out the name of the method (and nothing else).
Example invocations
TryIt.name();
TryIt.name();
should produce as output
name
name
Method longer() with specifcation
Return type: String;
Parameter list: two String parameters;
Action: returns the longer of its two string parameters (if the strings have the same length, it returns the first parameter).
Example invocation
String s = "CS";
String t = "1112";
String u = "BS";
String v = TryIt.longer( s, t );
String w = TryIt.longer( s, u );
System.out.println( v );
System.out.println( w );
should produce as output
1112
CS
Method absolute() with specifcation
Return type: void;
Parameter list: one ArrayList<Double> parameter;
Action: modifies the elements of its ArrayList<Double> parameter so that each element becomes its absolute value.
Suppose numbers represents an ArrayList<Double> with element values [ -3.0, 1.0, -4.0, 1.0, -5.0, 9.0 ]. Then the following code segment
Parameter list: one Random and two int parameters;
Action: returns a new ArrayList<Integer> whose elements are random integer values. The generator of the random values is gotten from its first parameter; the size of the new list is gotten from its second parameter; and the base from which the values are drawn is gotten from its third parameter.
Example usage
Random r1 = new Random( 11 );
Random r2 = new Random( 12 );
ArrayList<Integer> a = TryIt.generate( r1, 5, 10 );
ArrayList<Integer> b = TryIt.generate( r1, 5, 256 );
System.out.println( a );
System.out.println( b );
should produce as output
[ 8, 8, 1, 5, 3]
[102, 6, 232, 48, 73]
Class 25 — March 21, 2012
Neither cursing nor rehearsing, but
recursing
For general problem solving we also need the ability to control how
often actions are to be performed (looping). The while statement provides
this capability. We will see in later classes, that Java also provides
the for statement and do while statement for looping.
Some problem solving requires the ability to react. Different conditions need actions to be performed. Java provides several statements that support decision making. We begin by considering the if statement. The if statement uses a logical test expression to determine which of two actions should be performed.
Take the the busy time
survey to help me to decide
what day to offer the first test.
The links column to the left now has a link to
tests
Agenda
Sometimes when problem solving we need to represent a
collection/list of objects. To support such processing
Java provides the Collections Framework. The collections
framework consists both of a rich set of list
representations and an extensive set algorithms for
manipulating lists.
We explore today to list representations -- the ArrayList
and HashMap. They support respectively ordered lists
and associative lists.
Post class summary
The objects we have consider far each represented a single item -- be it a Scanner, Color, Random, or String object among others.
Sometimes we need to be able to represent a collection/list of objects.
There are different kinds of lists. I expect you know about sets. Sets are unordered lists — something is either in a set or its not. Since sets are unordered, we cannot
talk about the first thing in a set or the last thing in a set or the ith thing in a set.
I expect you also know about ordered lists. One kind of ordered list is a sequence. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are the first ten prime numbers. 2 is the first prime number,
3 is the second prime number, and so on.
Referring to an element in an order list is sometimes called subscripting.
For example, if x is an ordered list, people often denote the ith element
in the list as xi.
I also expect you are familiar with associative lists but do not know it. An associative list is a collection of mappings.
I like to think of an associative list as a dictionary. The list has a set of elements called keys, each of which is associated with some other value. The keys are words of the dictionary and the associated values are the definitions.
To support problem solving requiring list manipulation, Java provides the collection framework. The collection framework is part of the java.util library. The framework consists of possible list representations and an extensive collection of algorithms for manipulating lists.
Two of the most commonly used resources in the framework are ArrayList and HashMap.
An ArrayList is an ordered list.
A HashMap is an unordered associative list (i.e., a list of mappings).
ArrayList and HashMap are generics. A generic is not a class; a generic is a template from which classes can be formed.
When using a generic to generate a class, information about its intended usage is supplied. The information is given as parameters within angled brackets after the name of the generic.
When creating a new ArrayList we must indicate what type of objects will be kept in the list. The type of object is specified within angled brackets. For example,
ArrayList<String>
The ArrayList type whose elements are string objects
ArrayList<Color>
The ArrayList type whose elements are color objects
ArrayList<Double>
The ArrayList type whose elements decimal objects. Note, the capital D in Double.
Java requires that the elements of an ArrayList be objects. A lowercase double value is a number and not an object. Uppercase Double is Java's object representation of a decimal
ArrayList<Integer>
The ArrayList type whose elements are integer objects. Cannot use int for the same reason as decimal lists cannot use double.
An ArrayList object has at its disposal many different kinds of messages. They include
add()
Add another element to the list
remove()
Remove element from the list
size()
Report the size of the list (i.e., returns the number of elements in the list)
indexOf()
Reports the location of a value within the list (i.e., returns the index of the value within the list; if its not there, returns -1)
contains()
Reports whether a particular value is an element of the list (i.e., returns true or false depending whether the value is part of the list)
isEmpty()
Reports whether a list is empty( i.e., returns true or false depending whether the list has any elements)
clear()
Removes all elements from the list
When creating a new HashMap we must indicate what will be the form of the associations. The types are specified within angled brackets. For example,
HashMap<Color, String>
The HashMap type that associates colors with strings
HashMap<String, Color>
The HashMap type that associates strings with colors
HashMap<String, Integer>
The HashMap type that associates strings with other integers
HashMap<String, String>
The HashMap type that associates strings with strings
A HashMap object has at its disposal many different kinds of messages. They include
put()
Add another association to the collection
remove()
Remove an association from the collection
size()
Report the number of associations in the collection (i.e., returns the number of mappings in the collection)
get()
Reports what value some key maps to (i.e., returns the value associated with a key in the collection of mappings; if there is none, it returns null)
containsValue()
Reports whether there is an association for the key (i.e., returns true or false depending whether the key has an association in the collection)
containsKey()
Reports whether there is a key for the indicated value ( i.e., returns true or false depending whether there is a mapping from some key to the value in the collection of mappings)
clear()
Removes all associations from the collection
The Collections library provides algorithms for basic list processing; e.g., sorting, searching, and shuffling.
Suppose list is an ArrayList variable, then
Collections.sort( list )
Rearranges the order of the elements in list to put them in sorted order.
Collections.shuffle( list )
Randomly rearranges the ordering of the elements in list.
Last class did not go as intended. We had technical difficulties
and spent a lot of time on material that should have been part
of the readings.
As a result, we did not get as much time to problem solve as I
intended. Let's go for it today.
One thing we all need is for everyone to be prepared and present.
A third of the class had not done any recent reading and half
almost none — we cannot continue this way.
A recent paper on the effective teaching of large classes saw a nice
increase in student understanding if readings are accompanied
by exercises.
I created a retroactive on-line exercise sheet for the
previous class
and another for the
next class. Both must be
completed by Noon Monday.
Problem solve using multiple data sources — standard input (keyboard), text files, web pages, and strings
Use File for representing an element of file system
Use URL for representing locations of web resources
Next time
Section 2.1 — 2.8 – problem solving
Problem solving
The purpose of our tackling today
TwoLinesFromFile.java
is to hone your skills on string manipulation
Much of the data people need to consider
when problem solving is text. For example, the text may specify an input source or have
important information embedded within it.
An added benefit of developing the program is that it will help us prepare for a future assignment.
Program
TwoLinesFromFile.java
expects to be given an input source. That input source will
contain two lines. Both lines provide some necessary
information. All of the code for getting the two lines
are supplied for you. I did so, because this subtask is
not the interesting part.
// set up input scanner
Scanner stdin = new Scanner( System.in );
// get name of file to be processed
System.out.print( "What is your file: " );
String s = stdin.next();
// get a representation of the file
File f = new File( s );
// get connection to the file
Scanner reader = new Scanner( f );
// get data from the file
String line1 = reader.nextLine();
String line2 = reader.nextLine();
The first of the two input lines contains the name
of a JPG image; the second line contains a forecast.
On the first line, the start of the name of the JPG can be found immediately after the first
occurrence of the string "images/".
On that same line, the end of the name of the JPG can be found immediately before the first
double quote following the start of the name of the image.
On the second line, the start of the forecast can be found immediately after
the first occurrence of the string "</b>".
On that same line, the end of the forecast can be found immediately before the
first first occurrence of "<br>" following the start of forecast.
By storing the indices of the beginning and end of the image name, and
by also storing the indices of the beginning and end of the forecast,
substrings of the two lines can be gotten for acquiring the image name
and forecast.
// ******* get the indices for getting the jpg nameint i1 = 0;
int i2 = 0;
// ******* get the substring giving the name of the jpg
String jpg = "";
// ******* get the indices for getting the forecastint i3 = 0;
int i4 = 0;
// ******* get the substring giving the forecast
String forecast = "";
Here are four files to download to use for testing your effort.
Gain familiarity with object manipulation using strings as an exemplar
Next time
Section 2.3 — string manipulation
Survey
Take the super power survey. The survey will create a web page. If the indicated e-mail id was mst3k and the indicated power was Dinosaur metamorphosis, then web page
There are no String methods to change an existing String. There are many methods to produce new Strings.
'x' and "x" are different. The former is a char; the latter is a String.
null and "" are different. The former indicates a non-reference; the latter is a String with length 0.
A character string within double quotes is a String literal; e.g., "starting".
"name" and name are different. The former is a String literal; the latter is an identifier.
The characters in a String are accessible by their index. The first character has index 0, the second character has index 1, and so on.
Suppose
s, t, and u are strings,
m and n are integers.
then
s.length() is the number of characters in the character string represented by s.
s.charAt( m ) is a the char value of the character in s at index m.
s.trim() returns a new copy of character string s with any leading or trailing whitespace removed.
s.toLowerCase() returns a new copy of the character string s with any uppercase characters replaced by their lowercase counterparts.
s.toUpperCase() returns a new copy of the character string s with any lowercase characters replaced by their uppercase counterparts.
s.indexOf( t, m) returns the int value equal to the index of the first occurrence of t's character string within s's character string when starting the search at index m. If there is no occurrence then the value of the method is -1.
s.lastIndexOf( t, m ) returns the int value equal to the index of the last occurrence of t's character string within s's character string that starts on or before index m. If there is no occurrence then the value of the method is -1.
s.substring( m, n ) returns a new string representing the substring of s starting with its character at index m and continuing to the character with index n-1.
s.replace( t, u ) returns a new string formed by first copying all of the characters of s and then replacing all occurrences of substring t with string u.
s.replaceFirst( t, u ) returns a new string formed by first copying all of the characters of s and then replacing its first occurrence of the string pattern indicated by t with string u.
s.replaceAll( t, u ) returns a new string formed by first copying all of the characters of s and then replacing all occurrences of the string pattern indicated by t with string u.
s.compareTo( t ) returns an integer value indicating the lexicographical (alphabetical) relationship between s and t:
Returns 0 when s's character sequence is the same as t's character sequence;
Returns a negative value when s's character sequence occurs lexicographically before t's character sequence;
Returns a positive value when s's character sequence occurs lexicographically after t's character sequence;
s.equals( t ) returns a boolean value indicating whether s and t represent the same character sequence (i.e., do they look alike).
Also for your programming ease, there are some convenience methods
s.substring( m ) returns a new string representing the substring of s starting with its character at index m and continuing to the end of s.
s.indexOf( t ) is equivalent to s.indexOf( t, 0 ).
s.lastIndexOf( t ) is equivalent to s.lastIndexOf( t, m ), where m+1 is the length of character string represented by s.
Class 8 — February 3, 2012
Every picture tells a story
A major course goal is to enable you to develop your own problem
solving-specific
representations.
I believe to accomplish this goal you need background
experiences on the mechanics of object construction and manipulation.
The way I recommend
is that you use objects built from some of the standard
resources that are already available. Out of your experiences can come an
understanding and appreciation for the object-oriented approach.
We will begin with graphical elements for creating windows and drawing shapes
Objectify
Our initial exploration of objects will concentrate using some of classes from
java.util. java.awt, and javax.swing. The capabilities of these libraries allow
for
Popup windows
Graphical elements supporting the drawing and displaying of shapes,
texts, and images;
Random number generators;
File and URL support for accessing and writing image and text files;
Dictionaries and lists for data storage and manipulation.
When we need a new object, the first thing to do is to tell Java how to construct it. Afterwards, we can manipulate the object by sending it messages. A Java library designer must specify both the attributes its objects will have and which messages those objects can process.
Some messages to objects include information to assist the object in taking the right action. The information comes as parameters. Parameters are passed to a message through a parenthesized list following the message name. If there is more than one parameter, they are separated by commas.
Java requires a library designer to specify the types of and the order that parameters are to be given in a parameter list. To send a particular message, there must be a properly fill out parameter list. So be careful when sending a message to object that you know what and how it wants information to be passed.
Some objects send replies back for some of the messages they receive. Java requires a library designer to specify the type of reply (if any) a message will generate. In response to getting a message, an object will always reply back with a value of the type indicated by its designer. The reply is known as the message's return value.
While the expression 5 < 10 < 12 makes sense mathematically, it is not a legal Java expression. Why is that? Hint: look at the expression while being cognizant of operator precedence
Remember
Converting a decimal to an int requires a cast; e.g.,
int n1 = (int) ( Math.rint( x ) ); int n2 = (int) ( x );
General problem solving requires two-way communication; that is,
getting data and sending information back.
Java provides class Scanner as a means for
communicating with an input source.
Scanner is very flexible with regard to input sources.
Files, web pages, and user input are all acceptable.
We will explore today how to create and use Scanners that read user-supplied
numerical inputs.
A very basic way of getting input is to directly call for the user to supply it.
Java provides programmers with object System.in as the input counterpart
to System.out; that is, System.in is the Java representation of a user's keyboard.
When System.in is specified to be the input source for a Scanner, a program
can use the Scanner to process user input.
Your need to know
Scanner is part of the java.util standard library.
An import statement indicates that the software needs to make use of a library.
Import statements occur immediately before the class definition.
The statement
import java.util.*;
provides access to the entire java.util library.
Scanner is a class, but it is not a program. What we can get from it are Scanner objects.
A Scanner object can be directed to get information from an input source.
Java supplies the new operator to get a new object.
The act of setting up a new object is called construction.
The method that performs setting up is called a constructor.
A Scanner constructor can be given a parameter to specify the input source.
System.in is an input source associated with the keyboard.
The expression
new Scanner( System.in )
produces and constructs a new Scanner object that can read what the user enters.
The statement
Scanner stdin = new Scanner( System.in )
defines and initializes a Scanner variable named stdin. With the variable, a program can send messages to its object to read the next number, string, line of text, or logical value.
Every Scanner object has a method nextInt() for reading the next input as an integer value.
Every Scanner object has a method nextDouble() for reading the next input as a decimal value.
Class 4 — January 25, 2012
Hopping down the trail to computational thinking
Sophisticated problem solving requires the ability to abstract. A very basic part of abstraction is ability to name a value and to manipulate the value through a referencing of its name.
Continue our exploration of primitive types.
Introduce variables for naming locations in computer memory where values are stored.
Use definition statement to specify the name, type, and initial value associated with a variable.
Explore variable assignment.
Practice program modification.
For inquiring minds
Because any computer has a finite size, it is not possible for a computer to represent any possible value.
The creators of Java specified under normal circumstances that 32-bits of memory are used for storing integer values and that 64 bits of memory are used for storing decimal values.
As a bit has two possible values: 0 or 1, all numbers are represented internally as binary numbers. In fact all values are represented as binary numbers.
In representing a number Java reserves one bit for keeping track of the sign of the number. Therefore, for integers there are 31 bits for the number itself. The biggest 31-bit binary number is 1111111111111111111111111111111. That binary number equals the decimal number 232 - 1 = 2,147,483,647. The smallest 31-bit number is -2,147,483,648.
When doing calculations, the result can become too big or small. For example, 1000 * 1000 * 1000 * 1000 is one trillion, which is too big for 31 bits (computer scientists call that overflow). The 32-bit pattern produced doing the four multiplications of 1000 corresponds to -727379968.
FYI, the encoding for decimal numbers uses 52 bits for the number and 11 bits for the exponent. The biggest decimal number that can be represented is
21023 and the smallest positive nonzero value is 2-1074.
(Source Wikipedia)
In Java, a 32-bit integer is called an int value; a 64-bit decimal
number is called a
double value. int and double are types of values.
Java provides a logical type called boolean and a character type called char.
The char type is considered a numeric type.
The numeric and logical types are the Java primitive types. The other types of values in Java are object types.
An example of an object type is the String type.
Java provides addition (+), subtraction (-), multiplication (*) , division (/), and remainder (%) operators for its numeric types.
An int operation produces an int value; a double operation produces a double value; an operation with int and double values produces a double value.
Java provides the concatenation operator (+) for strings. The concatenation operator produces a new string by combining its operands.
Whenever one of the operands for a + operator is a string, it does concatenation; otherwise, it does numeric addition.
There are two possible boolean values: true and false. Java provides an and operator (&&), an or operator (||), and a not operator (!) for manipulating boolean values.
The && operator is true, when both of its operands are true; otherwise, the && operator is false.
The || operator is true, when at least one of its operands is true; otherwise, the || operator is false.
The ! operator produces the complement of its operand; i.e., ! true is false and ! false is true.
The argument to a println() or print() methods can be any Java expression that produces a value.
Early January 2012
The waiting is the hardest part
Practicing structured communication
Write an original, thoughtfulhaiku and electronically upload it using the class submission system by Noon Tuesday January 17 (the day before the start of classes).
In terms of structure a haiku is a three-line poem with the first line
being five syllables, the second seven syllables, and the third line being
five syllables. A haiku is not expected to rhyme.
A haiku is expected to paint an image regarding feelings and experiences.
Your haiku is to be about
your class expectations or concerns. The poem
should be appropriate for other class members to read. Students who do
not complete this assignment on time are subject to dismissal from
the class.
Software development
A major activity occurring throughout the semester is developing the ability to program in the Java language. In order for this to happen you need two pieces of software on your personal computer.
Java SDK (software development kit): the SDK will handle translating your instructions to computer code.
DrJava: a program development environment.
SDK
If you are a Windows user, you need to download and install the Java SDK. The SDK is a free download available from Oracle. There are two versions depending whether your laptop is running 32-bit or 64-bit windows. Most recent laptops are 64-bit. If you are unsure the 32-bit version works for all.
A handbook will be available from the bookstore. The handbook will contain an in-progress textbook and the major course examples. Please bring the handbook to every class meeting.