簡體   English   中英

如何使我的程序執行隨機方法?

[英]How do I get my program to do random methods?

我正在為Google Science Fair進行一個項目。 我正在制作一個使用兩個數字(條形碼和序列號)並使用各種算法將它們更改為兩個不同數字的應用程序(例如,像Fisher-Yates隨機播放)。 我的代碼看起來像這樣:

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中。 請幫忙。

使用策略模式。 讓每種算法實現該策略的版本。 然后,使用工廠使用所需的任何機制來獲得隨機策略實施。 無需將輸入組合到單個對象中。

我同意有關戰略和工廠模式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);

請注意,工廠是抽象的,並且具有靜態方法,這不是我要解決的方法,但是它將幫助您輕松而輕松地解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM