code java jmm
TRANSCRIPT
Jean Michel MEULIEN - Code Java Page 1
Code Java
Swing
La classe IHMMenu
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.Event;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.KeyStroke;
import java.awt.Point;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class IHMMenu {
private JFrame jFrame = null;
private JPanel jContentPane = null;
private JMenuBar jJMenuBar = null;
private JMenu fileMenu = null;
private JMenu editMenu = null;
private JMenu helpMenu = null;
private JMenu connexionMenu = null;
private JMenu editeurMenu = null;
private JMenuItem ouvrirItem = null ;
private JMenuItem exitMenuItem = null;
private JMenuItem aboutMenuItem = null;
private JMenuItem cutMenuItem = null;
private JMenuItem copyMenuItem = null;
private JMenuItem pasteMenuItem = null;
private JMenuItem saveMenuItem = null;
private JMenuItem connexionMenuItem ;
private JMenuItem editeurMenuItem ;
private JDialog aboutDialog = null;
private JPanel aboutContentPane = null;
private JLabel aboutVersionLabel = null;
Jean Michel MEULIEN - Code Java Page 2
private JScrollPane jScrollPane = null;
private JTable jTable = null;
JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setJMenuBar(getJJMenuBar());
jFrame.setSize(1717, 1475);
jFrame.setContentPane(getJContentPane());
jFrame.setTitle("Interface Homme Machine");
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getJScrollPane(), BorderLayout.EAST);
jContentPane.add(getJTable(), BorderLayout.NORTH);
jContentPane.setBackground(Color.RED);
}
return jContentPane;
}
/**
* This method initializes jJMenuBar
*
* @return javax.swing.JMenuBar
*/
private JMenuBar getJJMenuBar() {
if (jJMenuBar == null) {
jJMenuBar = new JMenuBar();
jJMenuBar.add(getFileMenu());
jJMenuBar.add(getEditMenu());
jJMenuBar.add(getHelpMenu());
jJMenuBar.add(getConnexionMenu());
jJMenuBar.add(getEditeurMenu());
}
return jJMenuBar;
}
/**
Jean Michel MEULIEN - Code Java Page 3
* This method initializes jMenu
*
* @return javax.swing.JMenu
*/
private JMenu getFileMenu() {
if (fileMenu == null) {
fileMenu = new JMenu();
fileMenu.setText("Fichier");
fileMenu.add(getouvrirMenuItem());
fileMenu.add(getSaveMenuItem());
fileMenu.add(getExitMenuItem());
}
return fileMenu;
}
/**
* This method initializes jMenu
*
* @return javax.swing.JMenu
*/
private JMenu getEditMenu() {
if (editMenu == null) {
editMenu = new JMenu();
editMenu.setText("Edition");
editMenu.add(getCutMenuItem());
editMenu.add(getCopyMenuItem());
editMenu.add(getPasteMenuItem());
}
return editMenu;
}
/**
* This method initializes jMenu
*
* @return javax.swing.JMenu
*/
private JMenu getHelpMenu() {
if (helpMenu == null) {
helpMenu = new JMenu();
helpMenu.setText("Aide");
helpMenu.add(getAboutMenuItem());
}
return helpMenu;
}
private JMenu getConnexionMenu() {
if (connexionMenu == null) {
connexionMenu = new JMenu();
connexionMenu.setText("IHM");
connexionMenu.add(getConnexionMenuItem());
}
Jean Michel MEULIEN - Code Java Page 4
return connexionMenu;
}
private JMenu getEditeurMenu() {
if (editeurMenu == null) {
editeurMenu = new JMenu();
editeurMenu.setText("Editeur ");
editeurMenu.add(getEditeurMenuItem());
}
return editeurMenu;
}
private JMenuItem getouvrirMenuItem() {
if (ouvrirItem == null) {
ouvrirItem = new JMenuItem();
ouvrirItem.setText("Ouvrir");
ouvrirItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.exit(0);
}
});
}
return ouvrirItem;
}
/**
* This method initializes jMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getExitMenuItem() {
if (exitMenuItem == null) {
exitMenuItem = new JMenuItem();
exitMenuItem.setText("Fermer");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
return exitMenuItem;
}
/**
* This method initializes jMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getAboutMenuItem() {
if (aboutMenuItem == null) {
Jean Michel MEULIEN - Code Java Page 5
aboutMenuItem = new JMenuItem();
aboutMenuItem.setText(" A PROPOS ");
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//la boite de dialogue va disparaitre car inutile mais nous conservons le code
JDialog aboutDialog = getAboutDialog();
aboutDialog.pack();
Point loc = getJFrame().getLocation();
loc.translate(20, 20);
aboutDialog.setLocation(loc);
aboutDialog.setVisible(true);
}
});
}
return aboutMenuItem;
}
private JMenuItem getConnexionMenuItem() {
if (connexionMenuItem == null) {
connexionMenuItem = new JMenuItem();
connexionMenuItem.setText("Interface Homme Machine ");
connexionMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
return connexionMenuItem;
}
private JMenuItem getEditeurMenuItem() {
if (editeurMenuItem == null) {
editeurMenuItem = new JMenuItem();
editeurMenuItem.setText("Affichage");
editeurMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
return editeurMenuItem;
}
/**
* This method initializes aboutDialog
*
* @return javax.swing.JDialog
*/
private JDialog getAboutDialog() {
if (aboutDialog == null) {
aboutDialog = new JDialog(getJFrame(), true);
aboutDialog.setTitle("A propos");
Jean Michel MEULIEN - Code Java Page 6
aboutDialog.setContentPane(getAboutContentPane());
}
return aboutDialog;
}
private JPanel getAboutContentPane() {
if (aboutContentPane == null) {
aboutContentPane = new JPanel();
aboutContentPane.setLayout(new BorderLayout());
aboutContentPane.add(getAboutVersionLabel(),
BorderLayout.CENTER);
aboutContentPane.setBackground(Color.RED);
}
return aboutContentPane;
}
private JLabel getAboutVersionLabel() {
if (aboutVersionLabel == null) {
aboutVersionLabel = new JLabel();
aboutVersionLabel.setText("Projet IHM ");
aboutVersionLabel.setHorizontalAlignment(SwingConstants.CENTER);
}
return aboutVersionLabel;
}
private JMenuItem getCutMenuItem() {
if (cutMenuItem == null) {
cutMenuItem = new JMenuItem();
cutMenuItem.setText("Couper");
cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
Event.CTRL_MASK, true));
}
return cutMenuItem;
}
private JMenuItem getCopyMenuItem() {
if (copyMenuItem == null) {
copyMenuItem = new JMenuItem();
copyMenuItem.setText("Copier");
copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
Event.CTRL_MASK, true));
}
Jean Michel MEULIEN - Code Java Page 7
return copyMenuItem;
}
private JMenuItem getPasteMenuItem() {
if (pasteMenuItem == null) {
pasteMenuItem = new JMenuItem();
pasteMenuItem.setText("Coller");
pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
Event.CTRL_MASK, true));
}
return pasteMenuItem;
}
/**
* This method initializes jMenuItem
*
* @return javax.swing.JMenuItem
*/
private JMenuItem getSaveMenuItem() {
if (saveMenuItem == null) {
saveMenuItem = new JMenuItem();
saveMenuItem.setText("Enregistrer");
saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Event.CTRL_MASK, true));
}
return saveMenuItem;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
}
return jScrollPane;
}
/**
* This method initializes jTable
*
* @return javax.swing.JTable
*/
private JTable getJTable() {
if (jTable == null) {
Jean Michel MEULIEN - Code Java Page 8
jTable = new JTable();
}
return jTable;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
IHMMenu appli = new IHMMenu();
appli.getJFrame().setVisible(true);
}
});
}
}
Swing
La classe Menus
import java.awt.*;
import javax.swing.*;
public class Menus extends JFrame {
public Menus(){
super( "Test des menus");
// Création de la barre de menu
JMenuBar barreMenu= new JMenuBar();
// Création du menu fichier
JMenu fichier= new JMenu( "Fichier");
// Création de l'option "Ouvrir" (option simple)
JMenuItem ouvrir= new JMenuItem( "Ouvrir");
fichier.add( ouvrir);
// Création du menu "Enregistrer" dont le label est en html
String labelEnregistrer= "<html><h1>Appuyer ici pour enregistrer</h1><br />"
+"Voici un menu <b> très particulier </b> en html !</html>";
JMenu enregistrer= new JMenu( labelEnregistrer);
// Spécification d'une police de caractères
enregistrer.setFont( new Font( "Times new roman", 0, 12));
fichier.add( enregistrer);
Jean Michel MEULIEN - Code Java Page 9
// Création d'une option à bouton radio
fichier.add( new JRadioButtonMenuItem( "Lecture seule"));
// On ajoute le menu fichier à la barre de menu
barreMenu.add( fichier);
// On ajoute au menu "Enregistrer" les trois options suivantes
// qui possèdent toutes les trois une icône
enregistrer.add( new JMenuItem( "Depuis fichier...",
new javax.swing.plaf.metal.MetalIconFactory.FileIcon16()));
enregistrer.add( new JMenuItem( "Depuis dossier...",
new javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon()));
enregistrer.add( new JMenuItem( "Rechercher...",
new javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon(true)));
// Ajout d'un item "check box" à la barre menu
barreMenu.add( new JCheckBoxMenuItem( "Checké"));
// La barre menu est mise sur la JFrame
setJMenuBar( barreMenu);
setBounds( 100, 100, 300, 150);
setVisible( true);
}
public static void main( String[] args) {
Menus menus= new Menus();
}
}
Scripts serveur JAVA (Servlets)
Le fichier html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Servlet</title>
</head>
<body>
<form method="post" action="http://localhost:8080/ProServlet/UserInfo" >
Jean Michel MEULIEN - Code Java Page 10
<table><tr><td> Nom: </td><td><input type="text" size="20" name="Nom" /> </td>
</tr>
<tr><td>Prénom: </td><td><input type="text" size="20" name="Prenom" />
</td></tr>
<tr> <td>Age: </td><td><input type="text" size="20" name="Age" /> </td> </tr>
<tr><td><input type="submit" name="envoyer" value="Envoyer" /> </td></tr>
</table>
</form>
</body>
</html>
La classe UserInfo (Servlet)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UserInfo
*/
@WebServlet("/UserInfo")
public class UserInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
Jean Michel MEULIEN - Code Java Page 11
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =response.getWriter();
out.println("<html> \n <head> <title> Récapitulatif </title>
</head><body> \n" +
"<h1>Récapitulatif des informations </h1> \n" +
"<ul>\n"+
"<li>Nom: "
+ request.getParameter("Nom") + "\n" +
"<li>Prenom: "
+ request.getParameter("Prenom") + "\n" +
"<li>Age: "
+ request.getParameter("Age") + "\n" +
"</ul> \n" + "</body></html>");
}
}
Les arbres binaires :
La classe Arbre public class Arbre
{
Arbre g;
String r;
Arbre d;
}
Jean Michel MEULIEN - Code Java Page 12
La classe Gestarb1
public class Gestarb1
{
// Primitives des arbres binaires
public static Arbre creerarbre(){ return null; }
public static Arbre construire( Arbre g0, String r0, Arbre d0 )
{
Arbre resultat=new Arbre();
resultat.g=g0; resultat.r=r0; resultat.d=d0;
return resultat;
}
public static boolean arbrevide(Arbre a){ return (a==null); }
public static Arbre gauche(Arbre a){ return a.g; }
public static String racine(Arbre a){ return a.r; }
public static Arbre droit(Arbre a){ return a.d; }
// visualisation du contenu d'un arbre binaire:
public static void affich( Arbre a, int decalage )
{
int i; if( !arbrevide(a) )
{
affich( gauche(a),decalage+4 );
for(i=1;i<=decalage;i++)System.out.print(" ");
System.out.println( racine(a) );
affich( droit(a),decalage+4 );
}
}
Jean Michel MEULIEN - Code Java Page 13
// construction pas à pas d'un arbre binaire:
public static void main(String [] args)
{
Arbre a1,a2; a1= new Arbre(); a2= new Arbre();
a1=construire(creerarbre(),"abc",creerarbre());
a2=construire(creerarbre(),"def",creerarbre());
a1=construire(a1,"xyz",a2);
affich(a1,0);
}
}
La classe Gestarb2
public class Gestarb2
{
// primitives des arbres binaires
public static Arbre creerarbre(){ return null; }
public static Arbre construire( Arbre g0, String r0, Arbre d0 )
{
Arbre resultat=new Arbre();
resultat.g=g0; resultat.r=r0; resultat.d=d0;
return resultat;
}
public static boolean arbrevide(Arbre a){ return (a==null); }
public static Arbre gauche(Arbre a){ return a.g; }
public static String racine(Arbre a){
return a.r; }
public static Arbre droit(Arbre a){
return a.d;
}
Jean Michel MEULIEN - Code Java Page 14
// visualisation du contenu d'un arbre binaire:
public static void affich( Arbre a, int decalage )
{ int i;
if( !arbrevide(a) )
{
affich( gauche(a),decalage+4 );
for(i=1;i<=decalage;i++)System.out.print(" ");
System.out.println( racine(a) );
affich( droit(a),decalage+4 );
}
}
// Insertion selon le principe de l'arbre binaire de recherche:
public static Arbre insere( String ch, Arbre a )
{
Arbre resultat= new Arbre();
if(arbrevide(a))
resultat=construire(creerarbre(),ch,creerarbre());
else if( ch.compareTo(racine(a))<0 )
resultat=construire(insere(ch,gauche(a)),racine(a),droit(a));
else
resultat=construire(gauche(a),racine(a),insere(ch,droit(a)));
return resultat;
}
// Construction d'un arbre binaire:
public static void main(String [] args)
{
Arbre a1; a1= new Arbre();
Jean Michel MEULIEN - Code Java Page 15
a1=creerarbre();
a1=insere("durand",a1);
a1=insere("dupond",a1);
a1=insere("smith",a1);
affich(a1,0);
}
}
Les Fichiers
// Gestion de fichier séquentiel de texte
La classe Gestfic3
import java.io.*;
public class Gestfic3
{
public static void main(String [] args)
throws IOException
{
int c;
FileReader entree = new FileReader("f0.txt");
FileWriter sortie = new FileWriter("f1.txt");
while( (c=entree.read()) != -1 ){
System.out.print(Integer.toString(c)+" ");
if( c==10 )System.out.println("");
sortie.write(c);
}
entree.close(); sortie.close();
}
}
Jean Michel MEULIEN - Code Java Page 16
La classe Gestfic4
import java.io.*;
public class Gestfic4
{
public static void main( String [] args ) throws IOException
{
BufferedReader f0; BufferedWriter f1; String ch;
f0=new BufferedReader( new FileReader("f0.txt") );
f1=new BufferedWriter( new FileWriter("f1.txt") );
while( (ch=f0.readLine()) != null )
{
System.out.println(ch);
f1.write(ch,0,ch.length()); f1.newLine();
}
f0.close(); f1.close();
}
}
La classe Gestfic5
import java.io.*;
public class Gestfic5 {
public static void main(String[] args) throws IOException
{
BufferedReader cnam;
BufferedWriter name;
BufferedWriter firstname;
String ch;
cnam = new BufferedReader(new FileReader("Cnam.txt"));
Jean Michel MEULIEN - Code Java Page 17
name = new BufferedWriter(new FileWriter("Name.txt"));
firstname = new BufferedWriter(new FileWriter("Firstname.txt"));
while ((ch = cnam.readLine())!= null){
name.write(ch,0,ch.length());name.newLine() ;
ch=cnam.readLine();
firstname.write(ch,0,ch.length());firstname.newLine();
}
cnam.close();name.close();firstname.close();
}
}
La classe Primitives
import java.lang.Thread;
//import java.awt.*;
//import javax.swing.*;
public class Primitives {
public static class T extends Thread {
//public void run(){
//int i;
//for(i=1;i<=5;i++){System.out.println(getName());
//try{sleep((long)2000);}
//catch(InterruptedException e){}
//}
//}
}
public void start(){}
public static void main(String[]args){
Jean Michel MEULIEN - Code Java Page 18
int i;
Thread t0;
t0 = Thread.currentThread();
T t1,t2;
t1 = new T();
t2 = new T();
t1.start();
t2.start();
for(i=1;i<=5;i++){System.out.println(t0.getName());
try{Thread.sleep((long)5000);}catch(InterruptedException e){}
}
}
}
Les fichiers
Cnam.txt
Meulien
Jean-Michel
Mani
Laure
Arnasdottir
Hanna
Apple
Golden
Ramuss
Maurice
Luistre
Hassa
Jean Michel MEULIEN - Code Java Page 19
Bergman
Brindis
Bourret
Gérard
Les fichiers f0.txt f1.txt
Macni
Laure
Meulien
Jean-Michel
Le fichier Firstname.txt
Jean-Michel
Laurent
Hanna
Golden
Manuel
Hassan
Brindis
Gérard
Le fichier Name.txt
Meulien
Macini
Arnasdottir
Apple
Raumois
El alibar
Bergman
Bourret
Jean Michel MEULIEN - Code Java Page 20
Les points et temps
La classe Point
public class Point {
protected double x;
protected double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point(Point p) {
this.x = p.x;
this.y = p.y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
Jean Michel MEULIEN - Code Java Page 21
}
public void negate() {
this.x = x * -1;
this.y = y * -1;
}
public double norm() {
return Math.sqrt(x * x + y * y);
}
public void move(double dx, double dy) {
x += dx;
y += dy;
}
public String toString() {
String str;
str = "x= " + x +";"+ "y = " + y;
return str;
}
}
La classe TestPoint
public class TestPoint {
public static void main(String[] args) {
Point p1,p2;
p1= new Point(3,4);
System.out.println(p1.toString());
}}
La classe TestTime
public class TestTime {
Jean Michel MEULIEN - Code Java Page 22
public static void main(String[] args) {
Time t1 =new Time(12,5,10);
t1.display();
t1.advance(2,57,55);
t1.display();
t1.advance(12,0,0);
t1.display();
t1.reset(12,5,10);
t1.display();
}
}
La classe Time
public class Time {
protected int h,m,s;
public Time() {
h=0;
m=0;
s=0;
}
public Time(Time theTime) {
this.h = theTime.h;
this.m = theTime.m;
this.s = theTime.s;
}
public Time(int h, int m, int s) {
reset(h,m,s);
}
Jean Michel MEULIEN - Code Java Page 23
public void advance(int h, int m, int s){
int t=((this.h+h)*3600+(this.m+m)*60 +this.s+s)%86400;
this.h=t/3600;
t=t-this.h*3600;
this.m=t/60;
this.s=t-this.m*60;
}
public void reset(int h, int m, int s){
this.h = h;
this.m = m;
this.s = s;
}
public void display(){
System.out.printf("%02d:%02d:%02d\n",h,m,s);
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
public int getM() {
return m;
}
public void setM(int m) {
this.m = m;
}
Jean Michel MEULIEN - Code Java Page 24
public int getS() {
return s;
}
public void setS(int s) {
this.s = s;
}
}
Les threads
La classe Etude2
public class Etude2 {
public static void main(String[] args) {
T1 t1 = new T1(); t1.start();
}
}
La classe Lire
import java.io.IOException;
public class Lire
{
public static String S() // Lire un String
{
String tmp = "";
char C='\0';
try {
while ((C=(char) System.in.read()) !='\n')
{
if (C != '\r') tmp = tmp+C;
Jean Michel MEULIEN - Code Java Page 25
}
}
catch (IOException e)
{
System.out.println("Erreur de frappe");
System.exit(0);
}
return tmp;
} // fin de S()
public static byte b() // Lire un entier byte
{
byte x=0;
try {
x=Byte.parseByte(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static short s() // Lire un entier short
{
short x=0;
try {
x=Short.parseShort(S());
}
Jean Michel MEULIEN - Code Java Page 26
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static int i() // Lire un entier
{
int x=0;
try {
x=Integer.parseInt(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static long l() // Lire un entier long
{
long x=0;
try {
x=Integer.parseInt(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
Jean Michel MEULIEN - Code Java Page 27
System.exit(0);
}
return x ;
}
public static double d() // Lire un double
{
double x=0.0;
try {
x=Double.valueOf(S()).doubleValue();
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static float f() // Lire un float
{
float x=0.0f;
try {
x=Double.valueOf(S()).floatValue();
}
catch (NumberFormatException e)
{
System.out.println("Format numérique incorrect");
Jean Michel MEULIEN - Code Java Page 28
System.exit(0);
}
return x ;
}
public static char c() // Lire un caractère
{
String tmp=S();
if (tmp.length()==0)
return '\n';
else
{
return tmp.charAt(0);
}
}
}
La classe T1
public class T1 extends Thread
{
public void run()
{
int i ; String rep ;
T2 t2 = new T2();
t2.start();
for (i=1;i<=5; i++)
{
System.out.println("T1, taper return pour réveiller processus T2");
Jean Michel MEULIEN - Code Java Page 29
rep= Lire.S();
t2.interrupt();
}
}
}
La classe T2
public class T2 extends Thread{
public void run(){
int i ;
for(i=1 ; i<= 10; i++){
System.out.println("T2 avant interruption");
try{sleep(20000);}catch(InterruptedException e){}
System.out.println("T2 aprés interruption");
}
}
}
Les Processus
La classe Gap_sema0
public class Gap_sema0 {
static Semaphore ab = new Semaphore(0);
static Semaphore ac = new Semaphore(0);
static Semaphore bd = new Semaphore(0);
static Semaphore ce = new Semaphore(0);
static Semaphore de = new Semaphore(0);
static Proc proc = new Proc();
Jean Michel MEULIEN - Code Java Page 30
public static class Ta extends Thread {
public void run(){
proc.a(); ab.v();ac.v();}
}
public static class Tb extends Thread {
public void run(){
ab.p(); proc.b(); bd.v();}
}
public static class Tc extends Thread {
public void run(){
ac.p(); proc.c(); ce.v();}
}
public static class Td extends Thread {
public void run(){
bd.p(); proc.d(); de.v();}
}
public static class Te extends Thread {
public void run(){
de.p();ce.p(); proc.e();}
}
public static void main(String[] args) {
Horloge h = new Horloge();h.start();
Ta a = new Ta(); a.start();
Tb b = new Tb(); b.start();
Tc c = new Tc(); c.start();
Td d = new Td(); d.start();
Jean Michel MEULIEN - Code Java Page 31
Te e = new Te(); e.start();
}
}
La classe Horloge
public class Horloge extends Thread{
public void run(){
int i;
System.out.println(" ");
try{sleep(500);}
catch (InterruptedException e ){}
for(i=0;i<=20;i++){
System.out.print(" \n "+ i +".5 : ");
try{sleep(1000);}
catch (InterruptedException e){}
}
}
}
La classe Proc
public class Proc {
public static void a(){
System.out.println("a début");
try{Thread.sleep((long)2000);}
catch( InterruptedException e){}
System.out.println("a fin");
}
public static void b(){
System.out.println("b début");
Jean Michel MEULIEN - Code Java Page 32
try{Thread.sleep((long)2000);}
catch( InterruptedException e){}
System.out.println(" b fin");
}
public static void c(){
System.out.println(" c début");
try{Thread.sleep((long)4000);}
catch( InterruptedException e){}
System.out.println(" c fin");
}
public static void d(){
System.out.println("d début");
try{Thread.sleep((long)8000);}
catch( InterruptedException e){}
System.out.println("d fin");
}
public static void e(){
System.out.println(" e début");
try{Thread.sleep((long)3000);}
catch( InterruptedException e){}
System.out.println("e fin");
}
}
La classe Semaphore
public class Semaphore {
private int valeur;
public Semaphore(int n){ valeur = n;}
Jean Michel MEULIEN - Code Java Page 33
public synchronized void p(){
while(valeur <= 0){
try { wait();} catch(InterruptedException e){}
}
valeur = valeur - 1;
}
public synchronized void v(){
valeur = valeur +1;
notify();
}
}
Les processus et les semaphores:
La classe Etude_trois
public class Etude_trois {
public static Semaphore mutex = new Semaphore(1);
public static class T extends Thread {
public int temporisation;
public T(String ch,int n){
super(ch);
temporisation = n;}
public void run (){
int i ;String ch= getName();
for (i=1;i<=5;i++){
try { sleep ((long)(1000*temporisation));}
catch (InterruptedException e){}
mutex.p();
System.out.println(ch+" Début de la Séction Critique : ");
Jean Michel MEULIEN - Code Java Page 34
try { sleep ((long)(2000*temporisation));}
catch (InterruptedException e){}
mutex.v();
System.out.println(ch+" Fin de la Séction Critique : ");
}
}
}
public static void main (String[]args){
Time h = new Time();
h.start();
T t1 = new T(" Premier :",1);
t1.start();
T t2 = new T(" Deuxième :",2);
t2.start();
T t3 = new T(" Troisième :",3);
t3.start();
}
}
La classe Lire
import java.io.IOException;
public class Lire
{
public static String S() // Lire un String
{
String tmp = "";
char C='\0';
try {
Jean Michel MEULIEN - Code Java Page 35
while ((C=(char) System.in.read()) !='\n')
{
if (C != '\r') tmp = tmp+C;
}
}
catch (IOException e)
{
System.out.println("Erreur de frappe");
System.exit(0);
}
return tmp;
} // fin de S()
public static byte b() // Lire un entier byte
{
byte x=0;
try {
x=Byte.parseByte(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static short s() // Lire un entier short
{
short x=0;
Jean Michel MEULIEN - Code Java Page 36
try {
x=Short.parseShort(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static int i() // Lire un entier
{
int x=0;
try {
x=Integer.parseInt(S());
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static long l() // Lire un entier long
{
long x=0;
try {
x=Integer.parseInt(S());
}
Jean Michel MEULIEN - Code Java Page 37
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static double d() // Lire un double
{
double x=0.0;
try {
x=Double.valueOf(S()).doubleValue();
}
catch (NumberFormatException e) {
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static float f() // Lire un float
{
float x=0.0f;
try {
x=Double.valueOf(S()).floatValue();
}
catch (NumberFormatException e)
{
Jean Michel MEULIEN - Code Java Page 38
System.out.println("Format numérique incorrect");
System.exit(0);
}
return x ;
}
public static char c() // Lire un caractère
{
String tmp=S();
if (tmp.length()==0)
return '\n';
else {
return tmp.charAt(0);
}
}
}
La classe Père_Fils2
public class Pere_Fils2 {
public static class T extends Thread {
public void Run() throws InterruptedException{
int i;
for(i=1;i<=20;i++){
try {sleep(5000);}
catch(InterruptedException e){}
System.out.println(getName()+" => attendre signal ");
try { sleep(100000);} catch( InterruptedException e)
{System.out.println(getName()+" => Le Signal est Arrivé : ");}
}
Jean Michel MEULIEN - Code Java Page 39
}
}
public static void main (String[]args){
Thread t0;
String ch;
int i;
T t1 = new T();
t1.setName("Fils1");
t1.start();
T t2 = new T();
t2.setName("Fils2");
t2.start();
t0 = Thread.currentThread();
t0.setName("pere");
for(i=1;i<=20;i++){
try{ Thread.sleep(6000);}catch(InterruptedException e){}
System.out.println(t0.getName()+ " : Reveiller \"Fils1\" ou \"Fils2\"?");
System.out.println(" Tapez au Clavier \"Fils1\"ou \"Fils2\",Puis
RETURN");
ch = Lire.S();
if( (ch.compareTo(" Fils1"))==0){
t1.interrupt();
ch = t0.getName();
System.out.println(ch+" => Le Signal est envoyé à Fils1");}
else {
t2.interrupt();
Jean Michel MEULIEN - Code Java Page 40
ch = t0.getName();
System.out.println(ch+" => Le Signal est envoyé à Fils2");}
}
}
}
La classe Semaphore
public class Semaphore {
private int valeur;
public Semaphore(int n){ valeur = n;}
public synchronized void p(){
while(valeur <= 0){
try { wait();} catch(InterruptedException e){}
}
valeur = valeur - 1;
}
public synchronized void v(){
valeur = valeur +1;
notify();}}
La classe Time
public class Time extends Thread{
public void run(){
int i;
System.out.println(" ");
try{sleep(500);}
catch (InterruptedException e ){}
for(i=0;i<=20;i++){
System.out.print(" \n "+ i +".5 : ");
Jean Michel MEULIEN - Code Java Page 41
try{sleep(1000);}
catch (InterruptedException e){}
}
}
}
Une applet
La classe AppletIHM
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
public class AppletIHM extends Applet implements ActionListener {
Panel p= new Panel();
Color c= Color.red;
public void init() {
setLayout( new BorderLayout());
p.setBackground( c);
add( "Center", p);
Button b= new Button( "Appuyer pour changer la couleur");
b.addActionListener( this);
add( "South", b);
}
public void actionPerformed( ActionEvent e) {
if( c.equals( Color.red))
c= Color.yellow;
else
c= Color.red;
p.setBackground( c);
}
}
Projet Hopital
La classe AjoutImpossible
public class AjoutImpossible extends Exception {
}
Jean Michel MEULIEN - Code Java Page 42
La classe Chambre
public class Chambre {
/* Variables d'instance */
private int numeroChambre; // numero de la chambre
//private int nbLits; // capacite en lits
private Patient[] tab; // tableau des patients
private int litOcc = 0; // nombre de lits occupes
/*
* Constructeur avec arguments: numC: numero de la chambre, n: le nombre de
* lits de la chambre
*/
public Chambre(int numC, int n) {
numeroChambre = numC;
tab = new Patient[n];
}
/* Accesseurs */
public int getNumeroChambre() {
return numeroChambre;
}
public int getCapacite() {
return tab.length;
}
public int getOccupation() {
return litOcc;
}
/* Tests */
Jean Michel MEULIEN - Code Java Page 43
public boolean estVide() {
return (getOccupation() == 0);
}
public boolean estPleine() {
return (getCapacite() == getOccupation());
}
/*
* Ajoute un patient.
*/
public boolean ajouterPatient(Patient p) throws AjoutImpossible {
if (this.estPleine())
throw new AjoutImpossible();
else {
tab[litOcc] = p;
litOcc++;
return true;
}
}
/* Affichages */
public void affiche() {
if (this.estVide()) {
Terminal.ecrireStringln("Aucun patient");
} else {
Terminal.sautDeLigne();
for (int i = 0; i < litOcc; i++) {
tab[i].afficher();
}
Jean Michel MEULIEN - Code Java Page 44
}
}
}
La classe Hôpital
public class Hopital {
/* Variables d'instance */
private String nom; // Nom
private Chambre[] chambres; // Tableau des chambres
// private int nbCh; // Nombre de chambres
// private int totalLits; // Nombre total de lits
// private int totalLitOcc; // Nombre total de lits occupes
// private int chPleines; // Nombre de chambres pleines
// private int chVides; // Nombre de chambres vides
private int nombreDeLitsOccupes = 0; // Nombre total de lits occupes
private int nombreDeChambresPleines = 0; // Nombre de chambres pleines
private int nombreDeChambresVides;
/**
* Nombre total de lits. A priori calculable facilement pour l'instant (4 *
* nombre De Chambres). Mais •a deviendrait plus complexe si les chambres
* n'avaient pas toutes le m•me nombre de lits.
*/
private int nombreTotalDeLits = 0;
/**
* Crée un hôpital toutes les chambres ont le même nombre de lits.
*
Jean Michel MEULIEN - Code Java Page 45
* @param nom
* nom de l'hôpital
* @param nombreDeChambre
* le nombre de chambres
* @param nombreDeLitsParChambre
*/
public Hopital(String nom, int nombreDeChambres, int
nombreDeLitsParChambre) {
initialiser(nom, nombreDeChambres, nombreDeLitsParChambre);
}
/**
* Méthode d'initialisation utilisée par les deux constructeurs. Nota: on
* pourrait aussi utiliser this() pour appeler le constructeur "normal" ˆ
* partir de celui qui utilise un tableau.
*
* @param nom
* @param nombreDeChambres
* @param nombreDeLitsParChambre
*/
private void initialiser(String nom, int nombreDeChambres,
int nombreDeLitsParChambre) {
this.nom = nom;
// totalLits = n * nlitsParCh;
// totalLitOcc = 0;
// chPleines = 0;
// chVides = nbCh;
chambres = new Chambre[nombreDeChambres];
Jean Michel MEULIEN - Code Java Page 46
for (int i = 0; i < nombreDeChambres; i++) {
chambres[i] = new Chambre(i, nombreDeLitsParChambre);
}
nombreTotalDeLits = nombreDeChambres * nombreDeLitsParChambre;
nombreDeChambresVides= nombreDeChambres;
}
/**
* Initialisation fictive d'après un tableau d'entiers.
* */
public Hopital(String nom, int nombreDeLitsParChambre, int[] t)
throws AjoutImpossible {
initialiser(nom, t.length, nombreDeLitsParChambre);
// Maintenant, on remplit les chambres...
String n = "p";
int ns = 1;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i]; j++, ns++) {
Patient p = new Patient(n + ns, ns);
ajouterPatient(p, i);
}
}
}
/* Accesseurs */
public String setNom() {
return nom;
Jean Michel MEULIEN - Code Java Page 47
}
public int getNombreDeChambres() {
return chambres.length;
}
public int getNombreDeChambresPleines() {
return nombreDeChambresPleines;
}
public int getNombreDeChambresVides() {
return nombreDeChambresVides;
}
/* Taux d'occupation */
public double getTauxDOccupation() {
return ((double) getNombreDeLitsOccupes()) / getNombreTotalDeLits();
}
public double getNombreDeLitsOccupes() {
return nombreDeLitsOccupes;
}
public double getNombreTotalDeLits() {
return nombreTotalDeLits;
}
Jean Michel MEULIEN - Code Java Page 48
/* Ajout des patients */
/*
* Ajout dans une chambre nCh. Retourne un boolean indiquant si l'ajout a pu
* se faire
*/
/**
* Teste s'il est possible d'ajouter un patient dans la chambre n.
*
*/
public boolean peutAjouterPatient(Patient p, int nCh) {
if (nCh > getNombreDeChambres() || nCh < 0 ||
chambres[nCh].estPleine())
return false;
else
return true;
}
/**
* Ajoute un patient dans une chambre donnée
*
* @param p
* @param numeroChambre
* @throws AjoutImpossible
* si la chambre est pleine.
*/
public void ajouterPatient(Patient p, int numeroChambre)
throws AjoutImpossible {
Jean Michel MEULIEN - Code Java Page 49
chambres[numeroChambre].ajouterPatient(p);
// Mise ˆ jour des variables d'instances:
this.nombreDeLitsOccupes++;
if (chambres[numeroChambre].getOccupation() == 1) {
nombreDeChambresVides--;
// La chambre Žtait vide, elle a maintenant un occupant.
}
if (chambres[numeroChambre].estPleine())
nombreDeChambresPleines++;
}
/**
* Retourne le numéro d'une chambre disponible parmi les chambres les plus
* remplies.
*
* @return le numéro de la chambre choisie, ou -1 si l'hôpital est plein.
*/
public int getChambreDisponible() {
int maxNonPlein = -1;
int indiceMaxNonPlein = -1;
for (int i = 0; i < chambres.length; i++) {
if (!(chambres[i].estPleine())
&& chambres[i].getOccupation() > maxNonPlein) {
indiceMaxNonPlein = i;
maxNonPlein = chambres[i].getOccupation();
}
}
// retourne -1 si on n'a pas trouvé de chambre,
Jean Michel MEULIEN - Code Java Page 50
// et le "meilleur" indice sinon.
return indiceMaxNonPlein;
}
/*
* Ajout dans une parmi les chambres les plus remplies. Retourne l'indice de
* la chambre, ou -1 si l'hôpital est plein.
*/
/**
* Ajoute un patient à l'hôpital.
*
* @return l'indice de la chambre o• le patient a été ajouté
* @throws AjoutImpossible si l'ajout est impossible.
*/
public int ajouterPatient(Patient p) throws AjoutImpossible {
int num = getChambreDisponible();
if (num != -1) {
ajouterPatient(p, num);
} else {
throw new AjoutImpossible();
}
return num;
}
/* Affichages */
public void affiche() {
Jean Michel MEULIEN - Code Java Page 51
Terminal.ecrireStringln("Hopital " + nom);
Terminal.ecrireStringln("Nombre de chambres = " +
getNombreDeChambres());
Terminal.ecrireStringln("Capacite en lits = " + getNombreTotalDeLits());
}
public void afficheStats() {
Terminal.ecrireStringln("Nombre lits occupes = "
+ getNombreDeLitsOccupes());
Terminal.ecrireStringln("Nombre chambres vides = "
+ getNombreDeChambresVides());
Terminal.ecrireStringln("Nombre chambres pleines = "
+ getNombreDeChambresPleines());
Terminal.ecrireStringln("Taux occupation = " + getTauxDOccupation());
}
public void afficheOccupation() {
Terminal.ecrireStringln("Nombre patients par chambre:");
for (int i = 0; i < chambres.length; i++) {
Terminal.ecrireStringln("Chambre " + i + ": "
+ chambres[i].getOccupation());
}
}
public void affichePatientsParChambre() {
Terminal.ecrireStringln("Patients par chambre:");
for (int i = 0; i < chambres.length; i++) {
Jean Michel MEULIEN - Code Java Page 52
Terminal.ecrireString("Chambre " + i + ": ");
chambres[i].affiche();
}
}
public void afficheTout() {
affiche();
afficheOccupation();
afficheStats();
affichePatientsParChambre();
}
}
La classe HopitalEntreeSorties
public class HopitalEntreeSorties {
/*
* Methodes statiques: saisit et retourne un patient
*
*/
public static Patient saisitPatient() {
Terminal.ecrireStringln("Saisie d'un patient");
Terminal.ecrireStringln("Nom? ");
String n = Terminal.lireString();
Terminal.ecrireStringln("Numero SS: ");
int ns = Terminal.lireInt();
return new Patient(n, ns);
}
}
Jean Michel MEULIEN - Code Java Page 53
La classe HopitalSansCache
public class HopitalSansCache {
/* Variables d'instance */
private String nom; // Nom
private Chambre[] chambres; // Tableau des chambres
// private int nbCh; // Nombre de chambres
// private int totalLits; // Nombre total de lits
// private int totalLitOcc; // Nombre total de lits occupes
// private int chPleines; // Nombre de chambres pleines
// private int chVides; // Nombre de chambres vides
/**
* Crée un hôpital o• toutes les chambres ont le même nombre de lits.
*
* @param nom
* nom de l'hôpital
* @param nombreDeChambre
* le nombre de chambres
* @param nombreDeLitsParChambre
*/
public HopitalSansCache(String nom, int nombreDeChambres,
int nombreDeLitsParChambre) {
this.nom = nom;
// totalLits = n * nlitsParCh;
// totalLitOcc = 0;
// chPleines = 0;
Jean Michel MEULIEN - Code Java Page 54
// chVides = nbCh;
chambres = new Chambre[nombreDeChambres];
for (int i = 0; i < nombreDeChambres; i++) {
chambres[i] = new Chambre(i, nombreDeLitsParChambre);
}
}
/* Accesseurs */
public String setNom() {
return nom;
}
public int getNombreDeChambres() {
return chambres.length;
}
public int getNombreDeChambresPleines() {
int nombreDeChambresPleines = 0;
for (int i = 0; i < getNombreDeChambres(); i++) {
if (chambres[i].estPleine())
nombreDeChambresPleines = nombreDeChambresPleines + 1;
}
return nombreDeChambresPleines;
}
public int getNombreDeChambresVides() {
int nombreDeChambresVides = 0;
for (int i = 0; i < getNombreDeChambres(); i++) {
if (chambres[i].estVide())
nombreDeChambresVides = nombreDeChambresVides + 1;
Jean Michel MEULIEN - Code Java Page 55
}
return nombreDeChambresVides;
}
/* Initialisation fictive d'apres un tableau d'entiers */
public void initialiseAvecTableau(int[] t) throws AjoutImpossible {
String n = "p";
int ns = 1;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i]; j++, ns++) {
Patient p = new Patient(n + ns, ns);
ajouterPatient(p, i);
}
}
}
/* Taux d'occupation */
public double getTauxDOccupation() {
return ((double) getNombreDeLitsOccupes()) / getNombreTotalDeLits();
}
public double getNombreDeLitsOccupes() {
int resultat = 0;
for (int i = 0; i < getNombreDeChambres(); i++) {
resultat = resultat + chambres[i].getOccupation();
}
return resultat;
}
Jean Michel MEULIEN - Code Java Page 56
public double getNombreTotalDeLits() {
int resultat = 0;
for (int i = 0; i < getNombreDeChambres(); i++) {
resultat = resultat + chambres[i].getCapacite();
}
return resultat;
}
/* Ajout des patients */
/*
* Ajout dans une chambre nCh. Retourne un boolean indiquant si l'ajout a pu
* se faire
*/
/**
* Teste s'il est possible d'ajouter un patient dans la chambre n.
*
*/
public boolean peutAjouterPatient(Patient p, int nCh) {
if (nCh > getNombreDeChambres() || nCh < 0 ||
chambres[nCh].estPleine())
return false;
else
return true;
}
/**
* Ajoute un patient dans une chambre donnŽe
Jean Michel MEULIEN - Code Java Page 57
*
* @param p
* @param numeroChambre
* @throws AjoutImpossible
* si la chambre est pleine.
*/
public void ajouterPatient(Patient p, int numeroChambre)
throws AjoutImpossible {
chambres[numeroChambre].ajouterPatient(p);
}
/**
* Retourne le numéro d'une chambre disponible parmi les chambres les plus
* remplies.
*
* @return le numéro de la chambre choisie, ou -1 si l'hôpital est plein.
*/
public int getChambreDisponible() {
int maxNonPlein = -1;
int indiceMaxNonPlein = -1;
for (int i = 0; i < chambres.length; i++) {
if (!(chambres[i].estPleine())
&& chambres[i].getOccupation() > maxNonPlein) {
indiceMaxNonPlein = i;
maxNonPlein = chambres[i].getOccupation();
}
}
// retourne -1 si on n'a pas trouvŽ de chambre,
Jean Michel MEULIEN - Code Java Page 58
// et le "meilleur" indice sinon.
return indiceMaxNonPlein;
}
/**
* Ajoute un patient ˆ l'hôpital.
*
* @return l'indice de la chambre o• le patient a été ajouté.
* @throws AjoutImpossible si l'ajout est impossible.
*
*/
public int ajouterPatient(Patient p) throws AjoutImpossible {
int num = getChambreDisponible();
if (num != -1) {
ajouterPatient(p, num);
} else {
throw new AjoutImpossible();
}
return num;
}
/* Affichages */
public void affiche() {
Terminal.ecrireStringln("Hopital " + nom);
Terminal.ecrireStringln("Nombre de chambres = " +
getNombreDeChambres());
Terminal.ecrireStringln("Capacite en lits = " + getNombreTotalDeLits());
}
Jean Michel MEULIEN - Code Java Page 59
public void afficheStats() {
Terminal.ecrireStringln("Nombre lits occupes = "
+ getNombreDeLitsOccupes());
Terminal.ecrireStringln("Nombre chambres vides = "
+ getNombreDeChambresVides());
Terminal.ecrireStringln("Nombre chambres pleines = "
+ getNombreDeChambresPleines());
Terminal.ecrireStringln("Taux occupation = " + getTauxDOccupation());
}
public void afficheOccupation() {
Terminal.ecrireStringln("Nombre patients par chambre:");
for (int i = 0; i < chambres.length; i++) {
Terminal.ecrireStringln("Chambre " + i + ": "
+ chambres[i].getOccupation());
}
}
public void affichePatientsParChambre() {
Terminal.ecrireStringln("Patients par chambre:");
for (int i = 0; i < chambres.length; i++) {
Terminal.ecrireString("Chambre " + i + ": ");
chambres[i].affiche();
}
}
public void afficheTout() {
Jean Michel MEULIEN - Code Java Page 60
affiche();
afficheOccupation();
afficheStats();
affichePatientsParChambre();
}
}
La classe HopitalTest
public class HopitalTest {
public static void main(String[] arguments) throws AjoutImpossible {
Hopital necker = new Hopital("Necker", 10, 4);
Terminal.ecrireStringln("Hopital avant initialisation");
necker.affiche();
int[] t = { 1, 3, 4, 0, 2, 3, 4, 4, 0, 1 };
String n = "p";
int ns = 1;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i]; j++, ns++) {
Patient p = new Patient(n + ns, ns);
necker.ajouterPatient(p, i);
}
}
Terminal.ecrireStringln("Hopital apres initialisation");
necker.affiche();
necker.affichePatientsParChambre();
Patient a1 = new Patient("Marie", 23879);
int ch = necker.ajouterPatient(a1);
Terminal.ecrireStringln("Marie dans la chambre " + ch);
Jean Michel MEULIEN - Code Java Page 61
necker.affiche();
necker.affichePatientsParChambre();
}
}
La classe Patient
public class Patient {
/* Variables d'instance privees */
private int numeroSecuriteSociale; // numéro sécurité sociale
private String nom; // nom
public Patient(String nom, int numeroSecuriteSociale) {
super();
this.nom = nom;
this.numeroSecuriteSociale = numeroSecuriteSociale;
}
/* Accesseurs */
public String getNom() {
return nom;
}
public int getNumeroSecuriteSociale() {
return numeroSecuriteSociale;
}
/* Affichages */
public void afficher() {
Terminal.ecrireString(" Nom: " + getNom());
Terminal.ecrireStringln(", Numero SS: " + getNumeroSecuriteSociale());
Terminal.sautDeLigne();
}
Jean Michel MEULIEN - Code Java Page 62
}
La classe Terminal
import java.io.*;
public class Terminal{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static String lireString() // Lire un String
{
String tmp="";
char C='\0';
try {
tmp = in.readLine();
}
catch (IOException e)
{
exceptionHandler(e);
}
return tmp;
} // fin de lireString()
public static int lireInt() // Lire un entier
{
int x=0;
try {
x=Integer.parseInt(lireString());
}
catch (NumberFormatException e) {
exceptionHandler(e);
}
Jean Michel MEULIEN - Code Java Page 63
return x ;
}
public static boolean lireBoolean() // Lire un entier
{
boolean b = true;
try {
b = Boolean.valueOf(lireString()).booleanValue();
}
catch (NumberFormatException e) {
exceptionHandler(e);
}
return b;
}
public static double lireDouble() // Lire un double
{
double x=0.0;
try {
x=Double.valueOf(lireString()).doubleValue();
}
catch (NumberFormatException e) {
exceptionHandler(e);
}
return x ;
}
public static char lireChar() // Lire un caractère
{
String tmp=lireString();
Jean Michel MEULIEN - Code Java Page 64
if (tmp.length()==0)
return '\n';
else
{
return tmp.charAt(0);
}
}
public static void ecrireString(String s){ // Afficher un String
try{
System.out.print(s);
} catch (Exception ex){
exceptionHandler(ex);
}
}
public static void ecrireStringln(String s) // Afficher un String
{
ecrireString(s);
sautDeLigne();
} // fin de ecrireStringln()
public static void ecrireInt(int i) // Afficher un entier
{
ecrireString(""+i);
}
public static void ecrireIntln(int i) // Afficher un entier
{
ecrireString(""+i);
sautDeLigne();
Jean Michel MEULIEN - Code Java Page 65
}
public static void ecrireBoolean(boolean b){
ecrireString(""+b);
}
public static void ecrireBooleanln(boolean b){
ecrireString(""+b);
sautDeLigne();
}
public static void ecrireDouble(double d) // Afficher un double
{
ecrireString(""+d);
}
public static void ecrireDoubleln(double d) // Afficher un double
{
ecrireDouble(d);
sautDeLigne();
}
public static void ecrireChar(char c) // Afficher un caractère
{
ecrireString(""+c);
}
public static void ecrireCharln(char c) // Afficher un caractère
{
ecrireChar(c);
sautDeLigne();
}
public static void sautDeLigne(){
Jean Michel MEULIEN - Code Java Page 66
try{
System.out.println();
}catch(Exception ex){
exceptionHandler(ex);
}
}
protected static void exceptionHandler(Exception ex){
TerminalException err = new TerminalException(ex);
throw err;
}
public static void ecrireException(Throwable ex){
ecrireString(ex.toString());
ex.printStackTrace(System.err);
}
}
class TerminalException extends RuntimeException{
Exception ex;
TerminalException(Exception e){
ex = e;
}
}
La classe TestHopital
public class TestHopital {
public static void main(String[] arguments) throws AjoutImpossible {
/* Initialisation d'après le tableau de l'exemple */
int[] t = { 1, 3, 4, 0, 2, 3, 4, 4, 0, 1 };
/* Creation de l'hopital: le tableau ET les chambres sont crees */
Jean Michel MEULIEN - Code Java Page 67
Hopital necker = new Hopital("Necker", 4, t);
/* Ajout "normal" d'un patient */
Patient a1 = new Patient("Marie", 23879);
// On cherche une chambre disponible...
try {
int numeroChambre= necker.ajouterPatient(a1);
Terminal.ecrireStringln("Marie dans la chambre " +
numeroChambre);
} catch (AjoutImpossible e) {
Terminal.ecrireStringln("Hopital plein. Ajout de Marie
impossible");
}
necker.afficheTout();
}}