Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package swap2randomnumbers;
- import java.util.Random;
- import java.util.Scanner;
- final class Pair {
- private Integer a, b;
- private final Random random;
- public Pair(Random random) {
- this.random = random;
- this.gen();
- }
- public void gen() {
- this.genA();
- this.genB();
- }
- public Integer getA() {
- return a;
- }
- public void setA(final Integer a) {
- this.a = a;
- }
- public void genA() {
- this.a = this.random.nextInt();
- }
- public Integer getB() {
- return b;
- }
- public void genB() {
- this.b = this.random.nextInt();
- }
- public void setB(final Integer b) {
- this.b = b;
- }
- }
- /**
- *
- * @author Aidan
- */
- public class Swap2RandomNumbers {
- static {
- renew_input();
- renew_random();
- }
- private static Random random;
- private static Scanner input;
- private static void renew_input() {
- input = new Scanner(System.in);
- }
- private static void renew_random() {
- random = new Random();
- }
- public static void main(String[] args) {
- Pair obj = new Pair(random);
- output(obj);
- //
- swap1(obj);
- output(obj);
- //
- obj.gen();
- output(obj);
- swap2(obj);
- output(obj);
- //
- obj.gen();
- output(obj);
- swap3(obj);
- output(obj);
- }
- private static void swap1(Pair x) {
- Integer tmp = x.getA();
- x.setA(x.getB());
- x.setB(tmp);
- }
- private static void swap2(Pair x) {
- /*
- a = a + b;
- b = a - b;
- a = a - b;
- */
- x.setA(x.getA() + x.getB());
- x.setB(x.getA() - x.getB());
- x.setA(x.getA() - x.getB());
- }
- private static void swap3(Pair x) {
- /*
- a = a ^ b;
- b = a ^ b;
- a = a ^ b;
- */
- x.setA(x.getA() ^ x.getB());
- x.setB(x.getA() ^ x.getB());
- x.setA(x.getA() ^ x.getB());
- }
- private static void output(Pair obj) {
- System.out.println("The pair is " + obj.getA() + " and " + obj.getB() + '.');
- System.out.flush();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement