lundi 8 juin 2015

Solving a java riddle

I'm given class A and class C, and I'm supposed to write class B which makes the output of the main in class C always successful! . Sine there is a random boolean variable, I get a good result only when it's false, when it's true I don't get an output. I'm not allowed to make any changes in class A or C.

I understand that the problem is in the third if in class C, but what changes I can make in class B to prevent from getting into this if?

    public class A {

    public String foo(String s) {
        return s;
    }
}

    public class B extends A {


    public A getA(boolean flag){
        A a = new A();
        if (flag){

            return(a);
        }
        else{
            return (a);
        }

    }

}


    package sw1.riddles.second;

import java.util.Random;

public class C {

    public static void main(String[] args) {
        String input = args[0];
        B b = new B();
        Random random = new Random();
        boolean randomBool = random.nextBoolean();
        A a = b.getA(randomBool);

        if (randomBool) {
            if (!input.equals(a.foo(input))) {
                return;
            }
        } else {
            if (!(input+input).equals(a.foo(input))) {
                return;
            }
        }
        System.out.println("success!");
    }
}

Aucun commentaire:

Enregistrer un commentaire