Download Slides - The University of Sydney

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
Java introduction
INFO1903
Wk 11b, sem1, 2014
Alan Fekete
Based on material by Alan Fekete and Michael Charleston
Copyright warning
COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to
you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the
Ac t ).
The material in this communication may be subject
to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under
the Act.
Do not remove this notice.
Java
•  Among the most widespread
programming languages today
•  Used for application development
•  Designed as a simplification of C++
–  for embedded systems
–  then popular for code to run in a browser
–  now mainly in enterprise settings
•  As part of the “Java ecosystem” with many
libraries, frameworks, tools
Example
Hello World
/**
*
*/
package intro;
/**
* @author mac
*
*/
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, world!");
System.out.println("This is really tedious... Hmm."
+ "What else can I do?");
for (int i = 0; i < 10; ++i) {
System.out.println(i + "^2 = " + (i*i));
}
}
}
~> javac intro/Demo.java
~> java intro/Demo
Hello, world!
This is really tedious... Hmm.
What else can I do?
0^2 = 0
1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
5^2 = 25
6^2 = 36
7^2 = 49
8^2 = 64
9^2 = 81
~>
Java has strong static types
•  Every variable must be declared before
being used, with its type
•  The type comes before the name
–  eg int height;
–  eg String fname;
Types
–  Every variable has an explicit type:
•  instance variables;
•  local variables in methods
–  Kinds of types: primitive, imported from
libraries, user-defined classes
•  examples include int, double, String, boolean,
Person, LinkedList<Person>
More places for types
•  Every method parameter must be typed
•  Every method must declare its return
type
– void means there is nothing returned
•  Eg String getFname() ...
•  Eg void setFname(String
newFname) ...
Syntax
•  The parsing of a Java program is driven
by keywords and special symbols
–  whitespace is unimportant (except to
separate words)
–  indentation is a matter of personal style
•  A declaration or statement is ended by
‘;’
More on Syntax
•  Statement blocks are indicated by ‘‘{...}’’
–  these can be nested
–  common trap (esp after editing):
indentation doesn’t match the code
structure
•  if, while etc are controlled by conditions
in ‘‘(...)’’
Example
triangles
4.1 Triangles "
This is a classic problem: given a single line of input containing a number, print a triangle of asterisks of that size. "
For example, given this input: "
5
"
1
Your program should print: "
"
2 ** "
3 *** "
4 **** "
5 ***** "
1
*
Here is some code that should help – this prints out a square: "
Program 0 (files/week4/problem4.1.py) "
1
size = int(raw_input("How big do you want the square? "))
2
for i in range(size):
3
print "*" * size
"
"
"
solution in Python
4.1 Triangles "
This one only required a few characters to change: "
Program 0 (files/week4/soln-4.1.py) "
size = int(raw_input("How big do you want the triangle? "))
for i in range(1, size + 1):
print ’*’ * i
solution in Java
package intro;
import java.util.Scanner;
public class Triangles {
public static void main(String[] args) {
int size; // you have to declare variables before you use them!
System.out.print("How big do you want the triangle? ");
// reading in from standard input can be fiddly:
Scanner in = new Scanner(System.in);
size = in.nextInt();
System.out.println("OK, " + size + " big.\n");
for (int i = 1; i <= size; ++i) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
~> javac intro/Triangles.java
~> java intro/Triangles
How big do you want the triangle? 5
OK, 5 big.
*
**
***
****
*****
~>
Java is dogmatically OO
•  A program consists of a set of classes
–  every function is a method of some class
–  Every statement is within some method of
some class
–  every variable is instance variable of a
class, or local variable in a method (or
static class-wide variable in a class)
OO or bust
•  The examples we give today take a
calculation, and place it in a method in a
class, because that is what Java insists
on
•  This code is not good OO style
–  See the following lecture
Example
counting words
4.2 Word counter "
Here’s something to help you not get too repetitive when writing essays. Write a program that reads multiple lines"
of plain text from standard input (not a file), then prints out each different word in the input with a count of how "
many times that word occurs. Don’t worry about punctuation or case – the input will just be words, all in lower "
case. Your output should list the words in alphabetical order. "
For example, given this input: "
1
which witch
is which
"
"
2
Your program should print this: "
1
is 1
"
"
3 witch 1 "
2
which 2
Program 1 (files/week4/soln-4.2.py)
"
import sys
occurrences = {}
line = sys.stdin.readline()
while line:
for word in line.split():
if word not in occurrences:
occurrences[word] = 1
else:
occurrences[word] += 1
line = sys.stdin.readline()
wordcounts = occurrences.items()
wordcounts.sort()
for word, count in wordcounts:
print word, count
package intro;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Map<String, Integer> occurrences = new HashMap<String, Integer>();
Scanner scanIn = new Scanner(System.in);
String [] line = (scanIn.nextLine().trim()).split("\\s");
while (!line[0].equals("")) {
for (String word : line) {
if (occurrences.get(word) == null) {
occurrences.put(word, 1);
} else {
occurrences.put(word, occurrences.get(word)+1);
}
}
line = (scanIn.nextLine().trim()).split("\\s");
}
for (String str : occurrences.keySet()) {
System.out.println(str + ", " + occurrences.get(str));
}
}
}
Java is compiled
•  Code then compile then run
•  But IDE does continuous compilation
•  Also, Java has reflection, so the running code
can construct new code and compile and link
with it!
•  You can compile any set of classes
–  each is called Classname.java
–  If compiler finds errors, it reports them
–  Else, it produces corresponding class files
•  Classname.class
Running
•  At execution time, a full set of class files
must be loaded into JVM, and execution
occurs
•  JVM also allows dynamic loading of extra class
files, as needed during running
•  Program typically gets input data and
produces output data
–  Console I/O, file system I/O, arguments
passed through main method call
Java development
•  You don't generally just run it from a
terminal
–  ok, hard-core people still use vim and
swear by it
•  For big, enterprise scale software
–  you use an integrated development
environment or IDE
look, here's one now
Example
igpay atinlay
4.3 igpay atinlay ilesfay "
Back in week 1 there was a problem about converting text to Pig Latin. "
Your task this week is to write a program that reads its input from a file called “input.txt” "
and prints out the file converted to Pig Latin. "
Here are the rules for converting words to Pig Latin: "
• If the word starts with a consonant, remove all consonants up to the first vowel, "
then add them to the end of the word followed by “ay”. "
So “strange” becomes “angestray”. "
• Words starting with vowels have “way” added to the end. "
All of our tests will be with files that contain lower-case words with no punctuation. "
Program 2 (files/week4/soln-4.3.py) "
for line in open(’input.txt’, ’rU’):
for word in line.split():
if word[0].lower() in "aeiou":
print word + "way",
else:
count = 0
while word[count].lower() not in "aeiou" and count < len(word):
count += 1
print word[count:] + word[:count] + ’ay’,
print "
package intro;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner in;
try {
in = new Scanner(new FileReader("input.txt"));
String vowels = "aeiou";
String [] line = null;
while (in.hasNext()) {
line = (in.nextLine().trim()).split("\\s");
for (String word : line) {
if (vowels.indexOf(word.charAt(0)) != -1) {
System.out.println(word + "way");
} else {
int count = 0;
while (vowels.indexOf(word.charAt(count)) != -1
&& count < word.length()) {
++count;
}
String pre = word.substring(0, count);
String post = word.substring(count);
System.out.println(post + pre + "ay");
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Example
finding genes
4.4 Genetic code "
You probably know that every cell in your body contains this amazing stuff called DNA. What you might not "
know is how similar the code of DNA is to the kind of digital data your programs have been manipulating so far "
in the Challenge. "
The problem here is to write a program that looks for patterns in DNA data from the Human Genome Project. "
Your program should read from a file called “sequence.dna”. Here is an example of what the data will look like "
(from human chromosome 6, if you’re interested): "
CATAACTAACAAAGCTGGGATACAAATTCGGTTCT
GTTTGGTTTTAGGGTCCAGTCTTTTATCTTCATTC
AAAGAGATAAATGGCCAATCTATATATCTATATCT
ATCTATCTATCTATCTATCTATCTATCTATCTATC
TATCTAATCTATCTTAGTTTAAGGTATTCTGAATT
CTTCAAACAATTTCTGCCATGAATAATTCCATCCC
Here are the patterns you’re looking for:
• GC signal: GGGCGG
• polyA signal: AATAAA
• CAAT signal: GG(C or T)CAATCT
•
"
TATA signal: TATA(A or T)A(A or T) "
If the file contains the pattern on the right, print the name of the pattern. "
There is nothing special about the line breaks, and your program needs to "
find matches that are partly on one line and partly on the next, but the input"
files will be small enough that you can read them into memory. "
For example, if the file contained the data above, your program should print
this: "
CAAT_signal
"
TATA_signal
It doesn’t matter what order the names are printed in, "
or if they are printed multiple times. "
Program 3 (files/week4/soln-4.4.py)
"
data = open(’sequence.dna’, ’rU’).read()
data = ’’.join(data.split())
genes = {
’GGCCAATCT’ : ’CAAT_signal’,
’GGTCAATCT’ : ’CAAT_signal’,
’GGGCGG’ : ’GC_signal’,
’AATAAA’ : ’polyA_signal’,
’TATAAAA’ : ’TATA_signal’,
’TATAAAT’ : ’TATA_signal’,
’TATATAA’ : ’TATA_signal’,
’TATATAT’ : ’TATA_signal’
}
for sequence in genes.keys():
if sequence in data:
print genes[sequence]
"
package intro;
import
import
import
import
import
java.io.FileNotFoundException;
java.io.FileReader;
java.util.HashMap;
java.util.Map;
java.util.Scanner;
public class GeneticCode {
static Map<String, String> genes = new HashMap<String, String>();
static {
genes.put("GGCCAATCT", "CAAT_signal");
genes.put("GGTCAATCT", "CAAT_signal");
genes.put("GGGCGG", "GC_signal");
genes.put("AATAAA", "polyA_signal");
genes.put("TATAAAA", "TATA_signal");
genes.put("TATAAAT", "TATA_signal");
genes.put("TATATAA", "TATA_signal");
genes.put("TATATAT", "TATA_signal");
}
public static void main(String[] args) {
try {
Scanner in = new Scanner(new FileReader("sequence.dna"));
String data = "";
while (in.hasNext()) {
data += in.next();
}
for (String seq : genes.keySet()) {
if (data.contains(seq)) {
System.out.println(genes.get(seq));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
summary
Java is
•  compiled:
–  write code -> compile -> run
•  statically typed
–  more testing at compile time
•  supported by IDEs
–  can take advantage of typing to help coding by
suggesting methods
•  Verbose and dogmatically OO
•  coming up next Semester in INFO1905/1105