Permuter deux variables en Java
Dans ce tutoriel nous allons découvrir deux façon pour permuter deux variables en Java. Soit avec ou sans variable temporaire.
[wx_adsense]
Exemple: Avec une variable temporaire
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int a, b, tmp;
System.out.print("Entrez deux nombres: ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
System.out.println("Avant la permutation: a = "+a+" et b = "+b);
tmp = a;
a = b;
b = tmp;
System.out.println("Aprés la permutation: a = "+a+" et b = "+b);
}
}
Sortie:

[wx_adsense]
Exemple: Sans variable temporaire
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
int a, b;
System.out.print("Entrez deux nombres: ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
System.out.println("Avant la permutation: a = "+a+" et b = "+b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("Aprés la permutation: a = "+a+" et b = "+b);
}
}
Sortie:

[wx_amazon]
