Download System.out.println(x)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Teaching programming at
Introductory Level
• Why has introductory computer science
courses become so advanced in terms
of conceptual materials presented
[Roberts04a]?
• Keeping a generation that has grown up
with XBox, PSP, Mobile Phone
Games… interested in our courses
requires a different approach.
• How to get them interested in computer
science?
How institutions attract students to CS
(ACM report)
• By allowing them to create similar applications in the first
year (at a high level of abstraction)
– Graphics
– Events and concurrent programming
– Distributed objects etc.
• Convince students at the end of first year
– Computing is Cool! Programming is Fun!
– I can do real life applications (Adam Boas)
• Leaving in-depth matters to be covered later
– Caching, Transactions, Building Components, Optimization …
– Sydney uni spends much of first year programming and design
• Institutions forced to adopt appropriate paradigms
• Java has proved to be suitable – but not without
problems
Role of ACM Java Task Force
• Java is widely taught as the first language. Most have moved
from “whether Java” to “if Java then how” ?
• Despite increasing usage “satisfaction is mixed”. Problems
common to all modern languages
•
Complexity associated with huge API
•
Instability – changing API, tools
• ACM Task Force formed to review the language, APIs, and tools
from the perspective of introductory computing education
• ACM Task Force to develop a stable collection of pedagogical
resources including a set of new packages. Feedback was invited.
What are the problems?
• Modern O-O languages caters to many demands trying
to meet user needs
• As a result the number of programming details a new
user has to must master has increased greatly (compare
with Pascal)
• Next program shows the number of constructs that must
be learnt even before they can get a simple program to
work using Java (earlier version).
–
–
–
–
Chaining
try catch block
Converting String to double
Use of special class for formatting output
BufferedReader Cannot read double directly
import java.io.*;
import java.text.*;
public class Add1
program
BR
{
static public void main(String args[])
{
InputStreamReader stdin = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(stdin);
double a = 0,b = 0, c;
String s1,s2;
try {
Try { } catch() { }
System.out.print("Enter value for a :");
Needed because
s1 = console.readLine();
readLine() may
a = Double.parseDouble(s1);
throw an
System.out.print("Enter value for b :");
s2 = console.readLine();
exception
b = Double.parseDouble(s2);
}
Though it will
catch(IOException ioex) {
not happens
System.out.println("Input error");
when reading
System.exit(1);
}
from keyboard)
c = a + b;
DecimalFormat dF = new DecimalFormat("0.00");
System.out.println(a + " + " + b + " = " + dF.format(c));
System.exit(0);
}
Needed to format output
}
Equivalent program in C
#include <stdio.h>
int main(int argc, char*argv[])
{
int a,b,c;
printf(“Enter values for a and b");
scanf("%d ",&a);
scanf("%d",&b);
c = a+b;
printf(“%d %d = %d\n",a,b,c);
}
How can J2SE 5 help?
import java.util.Scanner;
Use of Scanner class
public class Add2
requires no chaining
{
static public void main(String args[])
{
Scanner console = new Scanner(System.in);
double a,b, c;
System.out.print("Enter value for a and b :"); Scanner method reads
a = console.nextDouble();
numbers directly
b = console.nextDouble();
(patterns can be used)
c = a + b;
System.out.printf("%f + %f = %.2f",a,b,c);
New printf()
}
method makes
}
try {...} catch() {…} avoided
as no checked exception
thrown by Scanner methods
formatted
output simple
What are some new J2SE 5
features?
•
•
•
•
•
•
•
•
Scanner class
Formatted output
Using/Creating Generic classes
Autoboxing
Enhanced for loop
Type safe enum
Variable arguments
Static import
Using Generic classes
• All JCF classes can be used as generic classes
• For example, an ArrayList instance can be created to
store only Account objects by passing the type (Account)
to the constructor and the reference as in:
ArrayList<Account> accList =
new ArrayList<Account>();
• Similarly to map a customer name (String) to Account
objects we can use:
HashMap<String,Account> hashMap
= new HashMap<String,Account>();
Example using ArrayList
import java.util.*;
class Account { }
class Customer { }
public class TestGenericArray
{
public static void main(String[] args)
{
ArrayList<Account> accList = new ArrayList<Account>();
accList.add( new Account() );
accList.add( new Account() );
ArrayList<Customer> custList = new ArrayList<Customer>();
custList.add( new Customer() );
custList.add( new Customer() );
Compiler detects
custList.add( new Account() );
//
System.out.println("Entries in accList =" + accList);
System.out.println("Entries in custList =" + custList);
}
}
type mismatch
Autoboxing
•
Box/Unbox
–
•
Wrap a primitive into a class to be used as an object
and extract primitive value from object manually
AutoBox/AutoUnbox
–
Compiler does the work
ArrayList a = new ArrayList(10); Before
int num = 10;
a.add(new Integer(num));
int x = ((Integer)a.get(0)).intValue();
System.out.println(x);
JDK 1.5
With JDK 1.5
ArrayList<Integer> a = new ArrayList<Integer>(10);
int num = 10;
a.add(num);
int x = a.get(0);
System.out.println(x);
Boxing
UnBoxing
Enhanced for loop
• Iterations are made easy
• Before (iterating through a set)
Iterator iterator = set.iterator();
while ( iterator.hasNext())
System.out.print(iterator.next() + " ");
• With JDK 1.5
for (String s : set )
System.out.print(s + " ");
Variable Arguments
• Java 1.5 allows vararg specification
allowing any number of arguments
• It is of the form
– int… args
– String… messages
• You can have only one vararg in method
specifiction and it must be the last.
class Utility
Example: Variable Arguments
{
/**
Returns the largent of any number of int values
*/
public static int max(int... arg)
{
if ( arg.length == 0)
{ System.out.println("Error: Max of zero values");
System.exit(0);
}
int largest = arg[0];
for (int i=1; i<arg.length; i++)
if (arg[i] > largest )
largest = arg[i];
return largest;
}
}
public class TestUtility
{ public static void main(String args[])
{ int max1 = Utility.max(10,40,30);
int max2 = Utility.max(10,40,30,60);
System.out.println("max1 = " + max1 + " max2 = " + max2);
}
}
Type Safe enums
• Like C enum
• Type Safe
• Can be printed
import java.util.*;
public class Test3 {
enum WorkDay {MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY};
public static void main(String args[])
{
WorkDay meetingDay = WorkDay.THURSDAY;
System.out.println(meetingDay);
}
}
Static import
By adding a import statement for static
method you can avoid having to precede the
method with class name.
import static java.lang.Character.toUppercase;
toUpperCase(firstCharacter);
// instead of Character.toUpperCase(firstCharacter);
Remaining problems teaching/learning
(according to Java Task Force)
•
•
•
•
•
•
Scale
Instability (methods deprecated, new models)
Static methods
Exceptions
Conceptual difficulty of Graphics model
Writing event driven code
– due to event model
– due to difficulty of concurrent programming
Java Task Force Solutions
• Graphics Package
– Uses an extensible hierarchy of grapical objects
rooted at GObject
GTurtle
GCompound
GArc
GObject
GImage
GLabel
GPen
GOval
GRect
GPolygon
• Program Package
– Uses an hierarchy of Program classes
(ConsoleProgram, DialogProgram, GraphicsProgram)
• Others
ACM approach
Pros:
• Helps avoid overloading student with details
• Makes available pedagogical resources
• Beta version of JTF classes released
Cons
• Are we adding to the scale of complexity?
• Will will be chasing moving target (new features in Java
creates new problems)
• Can all staff agree on these or other classes (such as
developed by IBM) ?
• Availability of resources
Our own Java Task Force needed
Our challenge
Changing profile of students
• Students with high enter scores are
usually self-motivated
• Average students are willing to try
– If the problem is perceived to be interesting
– If it is not too difficult to get started
• Average students need more guidance
and feedback
Our Approach thus far
•
Use of helper classes / Container classes
to hide complexity in the initial stages
– ConsoleReader class
– Date class
– From this year JCF from first semester
•
Regular Assessments (9 excluding exam)
– Demos, WebLearn tests, MS-Test,
Assignments (3)
Our Approach thus far
Use some Animation, Games,
Robot Control, Aircraft Simulation
etc to motivate the students using a
layered Approach.
Diagram Editor
Layered Approach
Use given
Graphical objects
(emphasis on algorithms)
Student extend given
Graphical objects
(Emphasis OO Progr.)
BattleShip
Multiplayer Game
Students use
Swing classes
Emphasis GUI
Aircraft Landing
Students use
Threads, sockets, MVC,
RMI to design apps
How can our JTF help ?
• Study the ACM JTF classes and recommend adoption (or
otherwise)
• Assignments form very important part of student learning
and Java allows us to provide the required level of
abstraction to teach important concepts – but it takes
time.
• Develop and share pedagogical resources.
• Invite speakers from Industry and get student feedback.
Apr 4 speaker from Sun.
• Decide what Java features needs to be taught & the
depth.
• Avoid duplication in electives. Currently no Java course in
school (only used as a vehicle)
Discussion
A Parameterized Library class
The generic library class has a single type parameter E,
allowing it to store objects of type E.
Using parameterized type E
import java.util.*;
Uses the services of parameterized ArrayList
reference
Constructor
class Library<E>
{
private ArrayList<E> resources = new ArrayList<E>();
public void add(E x)
{
resources.add(x);
}
Allows any object of type E to be added
objects retrieved are of type E
public E retrieveLast() {
int size = resources.size();
if (size > 0) {
return resources.get(size-1);
}
return null;
}
}
Converting a class to Generic class
import java.util.*;
class Library {
private ArrayList resources =
new ArrayList();
public void add(Media x) {
resources.add(x);
}
public Media retrieveLast() {
int size = resources.size();
if (size > 0) {
return (Media)
resources.get(size-1);
}
return null;
}
}
public class TestLibrary
{ public static void main(String args[])
{ Library myBooks = new Library();
For
myBooks.add(new Book());
myBooks.add(new Book());
//
myBooks.add(new Video());
Book lastBook = (Book) myBooks.retrieveLast();
lastBook.print();
}
Explicit cast
}
needed
Media
Book
Video
storing Book objects
Cannot detect at
compile time resulting in
runtime error when
retrieving
Using the Parameterized Library
• When using the parameterized (generic) Library class a type must be
passes to the type parameter E.
• Note the element extracted from the parameterized Library need not
be cast.
No casting
needed
public class TestLibrary
Creating a Library to
{
public static void main(String args[]) store Book objects
{
Library<Book> myBooks = new Library<Book>();
myBooks.add(new Book());
myBooks.add(new Book());
Creating a Library to
Book lastBook = myBooks.retrieveLast();
store Video objects
lastBook.print();
Library<Video> myVideos = new Library<Video>();
myVideos.add(new Video());
myVideos.add(new Video());
myVideos.add(new Video());
Video lastVideo = myVideos.retrieveLast();
lastVideo.print();
}
}
Things to take note when creating
and using a Parameterized classes
• Primitive types cannot be passed as parameters.
ArrayList<Integer> numbers = new ArrayList<Integer>();
ArrayList<int> numbers = new ArrayList<int>();
• When a class uses parameterized type T, the type parameter T can
be used as a reference but not for constructing.
T object = …
T[] a = …
= new T();
= new T[10];
• The parameter can be used for casting
E e2 =(E) new Object();
E[] e3 = (E[])new Object[10];
• Generic classes cannot be array base type
Library<Video> videoLibs[] =
ArrayList<Video> vidLibs[] =
new Library<Video>[10];
new ArrayList<Video>[10];
References
[Roberts04a]
The dream of a common language: The
search for simplicity and stability in
computer science education. Proceedings
of the Thirty-Fifth SIGCSE Technical
Symposium on Computer Science
Education, Norfolk, VA, March 2004.