我遇到的问题是" slowRotor"返回值" Rotor_I"。
我想使用slowRotor(Rotor_I)的结果作为变量Rotor_I而不是"纯文本"可以这么说。
我想知道这是否可以在Java中使用,如果可以的话,它将如何完成(因为我试图避免大量的if语句)
<input type="text" name="some_input" data-target="toGrabInputViaJavaScript">
和
String slowRotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = "";
if (Rotor == "Slow") {
resultAfterRotor = Character.toString((slowRotor.charAt(position)));
}
答案 0 :(得分:0)
我不知道你想要什么,我们可以使用更多解释,但我猜测你的代码会是这样的:
if (rotor.equals("Slow")) {
resultAfterRotor = Character.toString((slowRotor.charAt(position)));
} else if (rotor.equals("Medium")) {
resultAfterRotor = // ... something else
} else if (rotor.equals("Fast")) {
resultAfterRotor = // ... something else
}
// ...
相反,您可以使用switch语句,避免像if-else-if-else-if那样对每个案例进行比较。 (虽然少数情况下(~~可能),但是开关将编译为if-else字节码,因为我认为这是最快的):
private final static String slowRotor = "EKMFLGDQVZNTOWYHXUSPAIBRCJ";
private final static String mediumRotor = "...";
private final static String fastRotor = "...";
public static void main(String[] args){
String rotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = getResultAfterRotor(rotor);
// ...
}
private String getResultAfterRotor(String rotor) {
switch(rotor){
case "Slow": {
return Character.toString(slowRotor.charAt(position));
}
case "Medium": {
return Character.toString(mediumRotor.charAt(position));
}
case "Fast": {
return Character.toString(fastRotor.charAt(position));
}
}
}
或者您可以使用地图
private static final Map<String, String> rotorMap = new HashMap<>();
static {
rotorMap.put("Slow", "EKMFLGDQVZNTOWYHXUSPAIBRCJ");
rotorMap.put("Slow2", "...");
rotorMap.put("Slow3", "...");
}
public static void main(String[] args){
String slowRotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = Character.toString(rotorMap.get(slowRotor).charAt(position));
// ...
}