PREVIOUS UP   Technologies Internet et Education, © TECFA
  5. Algorithmique de base

5. Algorithmique de base

5.1 Instructions les plus importantes

 

Nom

Fonctionalité

Voir:

assignation

assigner une valeur à une variable

5.3 "Assignation, type cast et expressions simples" [23]

for

"Pour faire"; faire N fois, etc.

5.4 "La répétition I: l'instruction for" [24]

if

"selection"; si alors sinon .....

5.5 "La sélection (if/else) et les conditionnels" [25]

while

"tant que faire", boucler tant qu'une condition soit remplie

5.7 "La répétition II (while)" [28]

try

"essayer" et si cela ne marche pas faire autre chose

5.8 "Les exceptions simples" [30]

expressions

calculer quelque chose, invoquer une méthodes etc.

5.9 "Classes et méthodes (encore une fois)" [32]

5.2 Les types de données

 

Max / ou valeurs possibles

Exemple

Initiatlisation par défaut

Nombres

byte

127

89

0

short

32767

-3

0

int

2147483647

10

0

long

10e18

10

0

float

10e38

123.456789

0.0

double

10e308

2.1

0.0

Autres

boolean

true false

true

false

char

A-Z,a-z,!@...

*

""

Vecteurs et Matrices

xxx []

-

int i [];

char tablo [] [];

selon le type

Classes Java

String

"......"

"Daniel S"

""

pleins d'autres !

5.3 Assignation, type cast et expressions simples

 

assignation simple

Exemples

variable = expression;

variable

voir aussi 5.2 "Les types de données" [22]

i

tree

expression

voir les manuels Java

x+y/10

"Sylvere M"

palm.enquiry()

vrai | faux

Exemple 5-1: Simple Calcul

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/SimpleCalculs.java
//
public class SimpleCalculs {                   

    // All programs must have main()
    public static void main(String[] args) { 

	int somme = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
	float moyenne = somme / 10;
	System.out.println ("La moyenne est égale à " +  moyenne);
	}
    } 

5.4 La répétition I: l'instruction for

 

For-statement

Exemples

for (start; check; update) {

body }

start

initialisations de variables d'itération

int I=0;

int Kaspar = 0;

check

condition qui teste s'il faut sortir de la boucle

i<10;

update

mise à jour de variables d'itération

i++;

ou i=i+a;

body

instruction ou bloc d'instructions

System.out.println(i + "fois,")

Exemple 5-2: Imprimer des messages un peu répétitifs

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/ForYou.java
public class ForYou {                   

    // All programs must have main()
    public static void main(String[] args) { 
	// Say hello!
	for (int i=1; i<11; i++) {
	    System.out.println("J'aimerai t'embrasser " + i + " fois\n ");    
	}
    }  
}  

5.5 La sélection (if/else) et les conditionnels

 

if

Exemples

if (condition)

bloc_d'instructions

else bloc_d'instructions

condition

( ..... )

(nombre > 1)

bloc_ d'instructions

{instruction; instruction; ....}
ou instruction_simple;
{ a = 1 + a;
  b = 2 + a; }
 

instruction simple

for (int i=1) { 
   System.out.println           ("forever");
 }

 

a = b;

Illustration:

if (thesecondstring.length() < thefirststring.length())
      {
        System.out.println("The second string is shorter");
      }
    else
      System.out.println("The second string is NOT shorter");

Exemple 5-3: Comparaison de la longeur de 2 strings

import java.io.*;
class Condition {
  /* A simple program to say what is the shortest string of two 
   * --------------------------    Java 1.1  Oct 1998 */

  public static void main (String [] args) throws IOException
{
    BufferedReader in = new BufferedReader
          (new InputStreamReader(System.in));

    System.out.println("Please: input a string");
    String thefirststring = in.readLine();
    System.out.println("Please: input another string");
    String thesecondstring = in.readLine();
    if (thesecondstring.length() < thefirststring.length())
      {System.out.println("The second string is shorter"); }
    else {
        if (thesecondstring.length() == thefirststring.length())
          { System.out.println("The two strings have the same length"); }
        else {
            System.out.println("The first string is shorter");
          }
      }
  }
}

5.6 Lire des nombres

Exemple 5-4: Lire un nombre

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/Sign.java

import java.io.*;

class Sign {
  /* A simple program to get the sign of a number 
   * --------------------------    Java 1.1  Oct 1998 */
  public static void main (String [] args) throws IOException, NumberFormatException
{
    BufferedReader in = new BufferedReader
          (new InputStreamReader(System.in));

    System.out.println("Please: input a number");
    Integer thenumber = new Integer(in.readLine());
    if (thenumber.intValue() < 0)
      {
        System.out.println("Negative number");
      }
    else
      {
        System.out.println("Positive number");
      }
  }
}

5.7 La répétition II (while)

 

while

Exemples

while (conditions) {

bloc_d'instructions

}

 

comme pour le "if"

(voir 5.5 "La sélection (if/else) et les conditionnels" [25]

Voici la logique d'un while:

Initialisation_des_conditions

while (conditions) {

bloc_d'instructions

changement_des conditions

}

a = 0;
while (a < 10) {
  n = n + a;
  a = a + 1;
  }

Illustration:

while (CurrentNumber.length()!=0) {
	TheSum = TheSum + (new Integer(CurrentNumber)).intValue();
	CurrentNumber=in.readLine();
    }

Exemple 5-5: Lire une série de nombres

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/Sum.java

import java.io.*;
class Sum {
    /* A simple program to get the sum of a list of numbers 
     * --------------------------    Java 1.1  Oct 1998 */
    public static void main (String [] args) throws IOException, NumberFormatException
    {

	BufferedReader in = new BufferedReader
	    (new InputStreamReader(System.in));
	System.out.println("Please:");
	System.out.println("Input a list of numbers, pressing enter between each number.");
	System.out.println("When you have finished, just press enter.");
	int TheSum = 0;
	String CurrentNumber = in.readLine();

	while (CurrentNumber.length()!=0)
	    {
		TheSum = TheSum + (new Integer(CurrentNumber)).intValue();
		CurrentNumber=in.readLine();
	    }
	System.out.println("The sum of all the numbers is " + TheSum);
    }
}

5.8 Les exceptions simples

 

 

Exemples

try {

bloc_d'instructions

}

catch (Signal_d'exception var) {

bloc_d'instructions

}

catch (Signal_d'exception var) {

bloc_d'instructions }

...

 

Signal d'exception

Signaux définies par le système

NumberFormatException

 

définis par vous-même

 

Illustration:

	try {
		Integer TheNumber = new Integer(in.readLine());
		System.out.println("The string you typed is a valid java number.");
	    }
	catch (NumberFormatException e)
	    {
		System.out.println("The string you typed is not a valid java number.");
	    }

Exemple 5-6: Lire un nombre et gérer les exceptions

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/Catch.java

import java.io.*;
class Catch {
    /* A simple program to read a string and tell if it is a valid java number
     * --------------------------    Java 1.1  Oct 1998 */
    public static void main (String [] args) throws IOException, NumberFormatException
    {
	BufferedReader in = new BufferedReader
	    (new InputStreamReader(System.in));
	System.out.println("Please: Input a number.");

	try
	    {
		Integer TheNumber = new Integer(in.readLine());
		System.out.println("The string you typed is a valid java number.");
	    }
	catch (NumberFormatException e)
	    {
		System.out.println("The string you typed is not a valid java number.");
	    }

    }
}

5.9 Classes et méthodes (encore une fois)

Exemple 5-7: Les palindromes

import java.io.*;
class Call {
    /* A simple program to show the way java methods are invoked 
     * --------------------------    Java 1.1  Oct 1998 */

    static String TheString;

    // constructor for the class
    Call () throws IOException
    {
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	System.out.println("Please:");
	System.out.println("Input a string");

	TheString = in.readLine();

	System.out.println("The palindrome is:");
	System.out.println(Palindromize1(TheString) + " (using method 1)");
	System.out.println(Palindromize2(TheString) + " (using method 2)");
	System.out.println("Hopefully, we get the same result");
    }

    // Simple Main method
    public static void main (String [] args) throws IOException
    {
	Call TheCall = new Call();
    }

    String Palindromize1 (String AString)
    {

	if (AString.length() < 2)
	    {
		return AString;
	    }
	else
	    {
// return the palindromized (2-last element) + 1st char
		return Palindromize1(AString.substring(1)).concat(AString.substring(0,1));
	    }
    }


    String Palindromize2 (String AString)
    {

	String ThePalindrome = new String();

	for (int i = (AString.length() - 1); i >= 0; i--)
	    {
		ThePalindrome = ThePalindrome.concat(AString.substring(i,i + 1));
	    }

	return ThePalindrome;
    }

}

5.10 Arrays et Tables

 

Simples tables

Exemple

 

int TheTable[] = new int[100];

Définit une table avec 100 éléments, chaque élément doit être un nombre entier.

Exemple 5-8: Lire des nombres et les mettre dans un tableau

http://tecfa.unige.ch/guides/java/staf2x/ex/basics/Table2.java


import java.io.*;

class Table2 {
    /* A VERY simple program to show how to use an array 
     * --------------------------    Java 1.1  Oct 1998 */

    public static void main (String [] args) throws                      IOException, NumberFormatException
    {
	BufferedReader in = new BufferedReader
	    (new InputStreamReader(System.in));
	System.out.println("Please:");
	System.out.println("Input a list of numbers, pressing enter between each number.");
	System.out.println("When you have finished, just press enter.");
	int TheTableLength = 0;
	int TheTable[] = new int[100];

	String CurrentNumber = in.readLine();
	while (CurrentNumber.length()!=0)
	    {
		TheTableLength = TheTableLength + 1;
		TheTable[TheTableLength - 1] = (new                     Integer(CurrentNumber)).intValue();

		CurrentNumber=in.readLine();
	    }
	System.out.println("The computer has a very big short term memory (100 elements max):");
	for (int i = 0; i < (TheTableLength); i++)
	    {
		System.out.print(TheTable[i] + " ");
	    }
    }
}

PREVIOUS UP -- TIE