我正在尝试在java中创建一个简单的密码来替换数组中的值,并将其替换为另一个数组中的值。一个是数字,下一个是字母。
我是Java的新手,就像上周的新手一样,我仍然在努力理解基础知识。我想办法做的唯一方法就是声明每个值及其等价物,是否存在更简单的方法是不添加25个不必要的代码行?我不太确定从哪里开始。任何帮助将不胜感激。
{-# LANGUAGE ConstraintKinds, TypeFamilies, UndecideableInstances,
UndecideableSuperclasses, FlexibleInstances
#-}
import GHC.Exts (Constraint)
import GHC.Prim (Any)
type family MaybeEq x :: Constraint where
MaybeEq (Maybe a) = Eq a
MaybeEq _ = Any -- A good "unsatisfiable" constraint
class MaybeEq a => K a where
instance MaybeEq a => K a where
答案 0 :(得分:0)
如果您想将每个号码与特定字符相关联;例如,每当程序看到“1”时它用“a”替换它,我会说你应该去找HashMap。 HashMap是一种数据结构,它存储Key和Key的两个东西。一个值。每个值都与一个键相关联,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]);
}
}
}
答案 1 :(得分:0)
我建议您使用Map并为每个条目应用密码逻辑。这样的事情:
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));
}