Esempio: Tombola! Parte seconda.

Slides:



Advertisements
Similar presentations
Uguaglianza equals() e clone(). Fondamenti di Java Uguali o identici?
Advertisements

Esempio: Tombola!.
Laboratorio di Linguaggi lezione X Marco Tarini Università dellInsubria Facoltà di Scienze Matematiche, Fisiche e Naturali di Varese Corso di Laurea in.
Input review If review Common Errors in Selection Statement Logical Operators switch Statements Generating Random Numbers practice.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
String Tokenization What is String Tokenization?
SCOPE & I/O CSC 171 FALL 2004 LECTURE 5. CSC171 Room Change Thursday, September 23. CSB 209 THERE WILL BE A (group) QUIZ! - topic: the CS department at.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
SELECTION CSC 171 FALL 2004 LECTURE 8. Sequences start end.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Java Review 3 Rem Collier. Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
CSC3170 Introduction to Database Systems
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java means Coffee Java Coffee Beans The name “JAVA” was taken from a cup of coffee.
Interfaces. –An interface describes a set of methods: no constructors no instance variables –The interface must be implemented by some class. 646 java.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
State Design Pattern. Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors.
Nested Classes CompSci 230 S Software Construction.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
James Tam Java Exception Handling Handling errors using Java’s exception handling mechanism.
Advanced Programming Practice Questions Advanced Programming. All slides copyright: Chetan Arora.
Exercise 1 Review OOP tirgul No Outline Polymorphism Exceptions A design example Summary.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Crash course in the Java Programming Language
A Java Program: // Fig. 2.1: Welcome1.java // Text-printing program.
Esempio: Tombola! Parte seconda.
Strings and File I/O.
CS1101: Programming Methodology Recitation 7 – Exceptions
Interactive Standard Input/output
Objects, Classes, Program Constructs
RADE new features via JAVA
CS Week 10 Jim Williams, PhD.
Operators Laboratory /11/16.
null, true, and false are also reserved.
Introduction to Java Programming
An Introduction to Java – Part I, language basics
L3. Necessary Java Programming Techniques
L3. Necessary Java Programming Techniques
Know for Quiz Everything through Last Week and Lab 7
class PrintOnetoTen { public static void main(String args[]) {
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Exception Handling Contents
Exceptions.
Clonazione La clonazione... Ovvero: come costruire una copia
Agenda Types and identifiers Practice Assignment Keywords in Java
Exceptions.
State Design Pattern.
Java Exception Handling
Presentation transcript:

Esempio: Tombola! Parte seconda

Publisher - Subscriber package tombola; public interface Publisher { public void subscribe(Object sender); public void unsubscribe(Object sender); public void notifyAll(Object x); } ------------------------------------------------------------ public interface Subscriber { public void getNotification(Object x);

Banco package tombola; import java.util.*; public class Banco implements Publisher { Random generatore; Set numeriUsciti; final int MAXNUM = 9; Collection subscriberSet; public Banco() { generatore = new Random(System.currentTimeMillis()/101); numeriUsciti = new HashSet(); subscriberSet = new HashSet(); }

Banco int getNextNumber() { boolean isNew = false; int num = 0; do { num = generatore.nextInt(MAXNUM) + 1; isNew = numeriUsciti.add(new Integer(num)); } while (!isNew); System.out.println("==> Estratto il numero:"+num); notifyAll(new Integer(num)); return num;

Banco public void subscribe(Object x) { subscriberSet.add(x); } public void unsubscribe(Object x) { subscriberSet.remove(x); public void notifyAll(Object x){ Iterator i=subscriberSet.iterator(); while (i.hasNext()) { ((Subscriber)i.next()).getNotification(x); public static void main(String[] args) { Banco banco1 = new Banco(); banco1.test(); } // end of class

Player package tombola; import java.util.*; public class Player implements Subscriber { Collection cartella; Collection cartellaOriginale; final int MAXNUM=9; final int NCELLS=3; String nome=null; Player(String nome){this.nome=nome;}

Player void creaNuovaCartella(int k){ Random generatore = new Random(System.currentTimeMillis()*k); cartella=new HashSet(); for (int i=1; i<=NCELLS; i++) { boolean creatoNuovoNumero=false; do { int x=generatore.nextInt(MAXNUM)+1; creatoNuovoNumero=cartella.add(new Integer(x)); } while (!creatoNuovoNumero); } cartellaOriginale=new TreeSet(); cartellaOriginale.addAll(cartella); mostraCartella();

Player public boolean checkNumber(int x) { boolean presente=cartella.remove(new Integer(x)); if (presente) { System.out.println(nome+" ha il numero "+x); } return presente; public boolean hasFinished() { if (cartella.isEmpty()) { System.out.println(nome+" ha finito!"); System.out.println("Aveva la seguente cartella:"); mostraCartella(); return true; } else return false;

Player public void mostraCartella(){ Iterator iter=cartellaOriginale.iterator(); while (iter.hasNext()) { System.out.print(iter.next()+" "); } System.out.println(nome); public void getNotification(Object x) { checkNumber(((Integer)x).intValue()); if (hasFinished()) System.exit(0);

Gioco public class Gioco { final int NUMPLAYERS=10; public Gioco() { Banco b1=new Banco(); Player p[]=new Player[NUMPLAYERS]; for (int i=0;i<NUMPLAYERS;i++){ p[i] = new Player("Pippo" + i); p[i].creaNuovaCartella(i); b1.subscribe(p[i]); } while (true) { b1.getNextNumber(); public static void main(String[] args) { Gioco gioco1 = new Gioco();

Gioco Pippo9 ha il numero 2 Pippo0 ha il numero 2 ==> Estratto il numero:5 Pippo4 ha il numero 5 Pippo2 ha il numero 5 Pippo6 ha il numero 5 Pippo9 ha il numero 5 ==> Estratto il numero:6 Pippo4 ha il numero 6 Pippo2 ha il numero 6 Pippo5 ha il numero 6 Pippo0 ha il numero 6 Pippo7 ha il numero 6 ==> Estratto il numero:1 Pippo2 ha il numero 1 Pippo2 ha finito! Aveva la seguente cartella: 1 5 6 Pippo2 2 6 7 Pippo0 2 7 8 Pippo1 1 5 6 Pippo2 2 4 7 Pippo3 5 6 8 Pippo4 3 4 6 Pippo5 4 5 7 Pippo6 6 7 8 Pippo7 3 4 7 Pippo8 1 2 5 Pippo9 ==> Estratto il numero:4 Pippo3 ha il numero 4 Pippo6 ha il numero 4 Pippo5 ha il numero 4 Pippo8 ha il numero 4 ==> Estratto il numero:2 Pippo3 ha il numero 2 Pippo1 ha il numero 2

Fondamenti di Java Static

Modificatori: static Variabili e metodi associati ad una Classe anziche’ ad un Oggetto sono definiti “static”. Le variabili statiche servono come singola variabile condivisa tra le varie istanze I metodi possono essere richiamati senza creare una istanza.

Variabili “static”: esempio 1 class S { static int instanceCount = 0; //variabile “di classe” S() {instanceCount++;} } public class A { public static void main(String a[]) { new A(); A() { for (int i = 0; i < 10; ++i) { S instance=new S(); System.out.println("# of instances: "+S.instanceCount); Output: # of instances: 10

Variabili “static”: esempio 2 class S { static int instanceCount = 0; //variabile “di classe” S() {instanceCount++;} public void finalize() {instanceCount--;} } public class A { public static void main(String a[]) { new A();} A() { for (int i = 0; i < 10; ++i) { S instance=new S(); System.out.println("# of instances: "+S.instanceCount); System.gc(); System.runFinalization(); Output: # of instances: 10 # of instances: 0

Metodi “static”: esempio 1 class S { static int instanceCount = 0; //variabile “di classe” S() {instanceCount++;} static void azzeraContatore() {instanceCount=0;} } public class A { public static void main(String a[]) { new A(); A() { for (int i = 0; i < 10; ++i) { if (i%4==0) S.azzeraContatore(); S instance=new S(); System.out.println("instanceCount: "+S.instanceCount); Può agire solo su variabili statiche! Output: instanceCount: 2 Ruolo: Metodi che agiscono su variabili statiche

metodi “static”: esempio 2 Math.sqrt(double x); System.gc(); System.arrayCopy(...); System.exit(); Integer.parseInt(String s); Float.parseFloat(String s); Notare la maiuscola! (per convenzione) Ruolo: analogo alle librerie del C Che cos’e’: System.out.println() ?

Perchè il main è “static”? public class A { String s="hello"; public static void main(String a[]) { System.out.println(s); } Non static variable s cannot be referenced from static context public class A { String s="hello"; public static void main(String a[]) { new A; } A() { System.out.println(s); hello

Input/Output, Eccezioni

Lettura di stringhe import java.io.*; public class A { public A() { Dammi una stringa abracadabra Hai scritto abracadabra import java.io.*; public class A { public A() { BufferedReader s = new BufferedReader( new InputStreamReader(System.in)); try { System.out.println("Dammi una stringa"); String str=s.readLine(); System.out.println("Hai scritto "+str); }catch (IOException e){ e.printStackTrace(); } public static void main(String [] ar) { A a=new A(); }

Lettura di int public A() { int i=0; BufferedReader s = new BufferedReader( new InputStreamReader(System.in)); try { System.out.println("Dammi un intero"); i=Integer.parseInt(s.readLine()); System.out.println("Hai scritto "+i); }catch (Exception e) {e.printStackTrace();} } Dammi un intero 2 Hai scritto 2

Lettura di int public A() { int i=0; BufferedReader s = new BufferedReader( new InputStreamReader(System.in)); try { System.out.println("Dammi un intero"); i=Integer.parseInt(s.readLine()); System.out.println("Hai scritto "+i); }catch (IOException e) {e.printStackTrace();} } Lettura di int Dammi un intero pippo java.lang.NumberFormatException: For input string: "gh" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:426) at java.lang.Integer.valueOf(Integer.java:532) at pila.A.<init>(A.java:11) at pila.A.main(A.java:19) Exception in thread "main"

Lettura di float public A() { float f=0; boolean error; BufferedReader s = new BufferedReader( new InputStreamReader(System.in)); try { do { System.out.println("Dammi un float"); try{ error=false; f=Float.parseFloat(s.readLine()); } catch (NumberFormatException e) { error=true; System.out.println("Input non valido"); } } while (error); System.out.println("Hai scritto "+f); }catch (IOException e) {e.printStackTrace();} Dammi un float pippo Input non valido 3 Hai scritto 3.0 Lettura di float

Lettura di stringhe con GUI import javax.swing.JOptionPane; public A() { ... String input = JOptionPane.showInputDialog( "How are you?"); System.out.println(input); System.exit(1); } Essenziale! Altrimenti la thread che gestisce la GUI rimane viva, e il processo non termina