我想acts
用一些枚举值填充数组.迭代时我想从控制台输入命令,但我的if语句找不到任何匹配,我总是得到输出"Incorrect"
.
我的代码:
Action[] acts = new Action[n];
for(int i = 0; i < n; i++) {
System.out.println("Enter act: ");
Scanner in1 = new Scanner(System.in);
String s = in1.next();
acts[i] = new Action();
if (s.equals("rotate_forw"))
acts[i].type = ActionType.RotF;
if (s.equals("rotate_back"))
acts[i].type = ActionType.RotB;
if (s.equals("shift_forw"))
acts[i].type = ActionType.ShiftF;
if (s.equals("shift_back"))
acts[i].type = ActionType.ShiftB;
else
System.out.println("Incorrect");
}
Run Code Online (Sandbox Code Playgroud)
您的else
条款只适用于过去的if
说法,所以你得到的"Incorrect"
输出,只要s.equals("shift_back")
是false
.
您的语句应替换为单个if-else-if ...- else语句,因此"Incorrect"
仅在所有条件为false
:
Action[] acts = new Action[n];
for(int i = 0; i < n; i++) {
if (s.equals("rotate_forw"))
acts[i].type = ActionType.RotF;
else if (s.equals("rotate_back"))
acts[i].type = ActionType.RotB;
else if (s.equals("shift_forw"))
acts[i].type = ActionType.ShiftF;
else if (s.equals("shift_back"))
acts[i].type = ActionType.ShiftB;
else
System.out.println("Incorrect");
}
Run Code Online (Sandbox Code Playgroud)
acts[i].type
当输入不正确时,您还应该考虑要分配的内容.也许你应该在这种情况下抛出异常.