如何让我的程序做随机方法?

时间:2014-05-05 16:14:36

标签: java algorithm user-interface encryption methods

我正在为谷歌科学博览会开展一个项目。我正在制作一个带有两个数字(条形码和序列号)的应用程序,并使用各种算法将它们改为两个不同的数字(即像Fisher-Yates shuffle一样)。 我的代码看起来像这样:

enter code here public static void main(String[] args) {
    reverseNum b = new reverseNum();
    addOne   c= new addOne();
    plusThree f= new plusThree();
    plusNine  i = new plusNine();
    plusTwo l = new plusTwo();
    minusTwo  p = new minusTwo();
    plusOne  r= new plusOne();
    plusFour u= new plusFour();
    threeTwo x= new threeTwo();
    intoTwo  ab= new intoTwo();
    plusFive bc = new plusFive();
    intoSix cd= new intoSix();
     twoOne de = new twoOne() ;
    plusSeven ef= new plusSeven();
    plusEight fg= new plusEight();
    minOne gh = new minOne();
    intoSeven hi = new intoSeven();
    intoEight ij = new intoEight();
    intoNine jk = new intoNine();
    intOne kl = new intOne();
    intoFour lm = new intoFour();
    // TODO code application logic here
    Scanner user_input = new Scanner( System.in );
    String a ;
      System.out.println("Enter the Barcode:");
 a = user_input.next();
         System.out.println("Encrypted Barcode:"+ blah.randomMethod(a));
         //Random method from the above given methods should modify this.
         String z;
         System.out.println("Enter the Serial Number:");
         z= user_input.next();
         System.out.println("Encrypted Serial Number:" + blah.randomMethod(z) );
         //Random method from the above given methods should modify this
}

}

我的主要目标是使用上述方法(算法)修改两个给定的数字。我希望每次用户运行程序时,给定列表中的随机方法修改给定的数字。我还需要把这一切都放到GUI中。请帮忙。

2 个答案:

答案 0 :(得分:2)

使用策略模式。让每个算法实现该策略的版本。然后使用工厂使用您想要的任何机制获得随机策略实现。无需将输入组合到单个对象中。

答案 1 :(得分:2)

我同意 jgitter 关于策略和工厂模式。

我发布了一个例子。

public interface Algorithm {
     public String execute(String input);
}

public class SomeAlgorithm implements Algorithm {

     public String execute(String input) {
         ///... Algorithm here
     }
}

public class AnotherAlgorithm implements Algorithm {

     public String execute(String input) {
         ///... Algorithm here
     }
}

public abstract class AlgorithmFactory {
     public static Algorithm createRandomAlgorithm() {

         //Create a new Random object
         Random randomEngine = new Random();

         //Retrieve a number from 0 (inclusive) to 2 (exclusive)
         int randomNumber = randomEngine.nextInt(2);

         //Select which implementation to use according to the random number
         switch(randomNumber) {
             case 0: return new SomeAlgorithm();
             case 1: return new AnotherAlgorithm();
         }

         //This will most likely never get called, but a return value is mandatory
         return null;
     }
}

然后,您将检索并执行如下算法:

String encryption = AlgorithmFactory.createRandomAlgorithm().execute(input);

请注意,工厂是抽象的,并且有一个静态的方法,这不是我接近这个的方法,但它会很好地帮助你解决问题。

相关问题