簡體   English   中英

Java中的簡單密碼程序

[英]A simple cypher program in java

我正在嘗試在java中創建一個簡單的密碼,該密碼將替換數組中的值,並將其替換為另一個數組中的值。 一個是數字,第二個是字母。

我對Java非常陌生,就像上周剛接觸Java,但我仍在嘗試了解基礎知識。我想做到這一點的唯一方法是聲明每個值及其等效項,還有一種更短的方法這樣做無需添加25條多余的代碼行? 我不太確定從哪里開始。 任何幫助將不勝感激。

 class simpleCypher {

   String[] alpha;
    String[] numo;

    public static void main(String args[]) {
    String[] numo = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
            "12", "13", "14", "15", "16", "17", "18",
            "19", "20", "21", "22", "23", "24", "25", "26",};
    String[] alpha = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r",
            "s", "t", "u", "v", "w", "x", "y", "z", };

    numo[21] = alpha[21];       
    System.out.println(numo[21]);


    }
}

如果您想將每個數字與一個特定字符相關聯; 例如,每次程序看到“ 1”時,它就會用“ a”替換它,我想說您應該使用HashMap。 HashMap是一種存儲鍵和值兩件事的數據結構。 每個值都與一個鍵相關聯,並且HashMap將唯一鍵映射到值。

代碼如下:

class simpleCypher {

private static HashMap<String, String> hMap = new HashMap<>();

public static void main(String[] args){
    hMap.put("1", "a");
    hMap.put("2", "b");
    hMap.put("3", "c");
    // continue adding ...

    String[] numo = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
            "12", "13", "14", "15", "16", "17", "18",
            "19", "20", "21", "22", "23", "24", "25", "26",};


    for (int i = 0; i<numo.length ; i++){
        numo[i] = hMap.get(numo[i]);
        System.out.println(numo[i]);
    }
}
}

我建議您使用映射,並對每個條目應用密碼邏輯。 像這樣:

  public static void main(String args []) {
    Map<Integer, Integer > map = new HashMap<>();

    for ( int i = 1; i <= 25; i ++ ){
      // do whatever you want in the logic
      int cypher = i * i + 1;
      map.put(i, cypher);
    }

    map.values().stream().forEach(cypher -> System.out.println(cypher));
  }

暫無
暫無

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

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