Ira Nazarchuk Ira Nazarchuk - 13 days ago 8
Java Question

Scanner strings equality

I want to fill the array with values of some enum. While iterating I want to input commands from console, but if statements don't find any match and the output is always "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");
}

Answer

Your else applies only to the last if, so you get the "Incorrect" output whenever s.equals("shift_back") is false.

Your statements should be replaced with a single if-else-if...-else statement, so that "Incorrect" is only printed if all the conditions are false :

    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");

You should also consider what you want to assign to acts[i].type when the input is incorrect. Perhaps you should throw an exception in this case.