lundi 17 mai 2021

How to condense code with a sequence of lists in Java?

For a class project, we were tasked with creating a program that would give us the way to defuse a certain module in the game called "Keep Talking and Nobody Explodes". I was tasked with creating a program that would solve the keypad module. I have come up with the solution below.

How can I condense this long line of if-statements to find which list(rowOne, rowTwo, etc.) matches up with the user-entered list(input)?

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<String> input = new ArrayList<>();
        System.out.println("Enter the names of the four symbols");
        for(int i = 0; i < 4; i++) {
            input.add(sc.nextLine());
        }

        List<String> rowOne = List.of("balloon", "at", "upsidedowny", "squigglyn", "squidknife", "hookn", "leftc");
        List<String> rowTwo = List.of("euro", "balloon", "leftc", "cursive", "hollowstar", "hookn", "questionmark");
        List<String> rowThree = List.of("copyright", "pumpkin", "cursive", "doublek", "meltedthree", "upsidedowny", "hollowstar");
        List<String> rowFour = List.of("six", "paragraph", "bt", "squidknife", "doublek", "questionmark", "smileyface");
        List<String> rowFive = List.of("pitchfork", "smileyface", "bt", "rightc", "paragraph", "dragon", "filledstar");
        List<String> rowSix = List.of("six", "euro", "tracks", "ae", "pitchfork", "nwithhat", "omega");

        if(rowOne.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowOne);
            copy.retainAll(input);
            System.out.println(copy);
        }
        if(rowTwo.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowTwo);
            copy.retainAll(input);
            System.out.println(copy);
        }
        if(rowThree.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowThree);
            copy.retainAll(input);
            System.out.println(copy);
        }
        if(rowFour.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowFour);
            copy.retainAll(input);
            System.out.println(copy);
        }
        if(rowFive.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowFive);
            copy.retainAll(input);
            System.out.println(copy);
        }
        if(rowSix.containsAll(input)) {
            List<String> copy = new ArrayList<>(rowSix);
            copy.retainAll(input);
            System.out.println(copy);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire