0
votes

Comment supprimer un élément l'entrée de l'utilisateur d'une arracheListe lorsqu'elle contient des chaînes et des entiers?

Je suis nouveau au codage et je suis assez confus de la façon dont cette arraylist fonctionne.

J'ai le [Java] Code: P>

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();

allCards.remove(new Integer(i));


4 commentaires

Remarque: vous devez utiliser la méthode d'usine integer.valueof en faveur du constructeur. Cela exploite le cache entier , fournissant un gain de performance.


@Mcemperor ou juste passer je, ce qui ferait exactement ça.


@MAURICEPERRY Non, qui ne fonctionnera pas , car le Supprimer (objet O) est surchargé par Supprimer (Index Index) , qui fait Ne retirez pas l'objet spécifié, mais l'élément à l'index spécifié à la place. J'avoue que c'est un méchant, mais cela compte pour ce cas particulier. Dans ce cas, si i avait la valeur 3 et allcards.remove (i) a été appelé, puis le k serait supprimé.


@Mcemperor OK. Mon erreur.


5 Réponses :


-3
votes

Vous pouvez utiliser COLLECTION.REMOVEIF :

allCards.removeIf(obj -> obj instanceof Integer);


0 commentaires

0
votes

Je pense que votre problème peut être résolu si vous utilisez simplement une arraylist avec type de chaîne comme: xxx pré>

sur la manière de supprimer l'élément dans la liste des matrices, vous pouvez obtenir une entrée de l'utilisateur dans String, puis comparez-la aux éléments de la liste des matrices. Lorsque vous utilisez la méthode Supprimer () si la chaîne d'entrée correspond (sensible à la casse) de l'élément, il ne supprimera que la première occurrence, sinon, ce n'est pas la chose. Vous pouvez tester ce code: P>

    ArrayList<String> allCards = new ArrayList<String>();
    allCards.add("2");
    allCards.add("2");
    allCards.add("3");
    allCards.add("K");
    allCards.add("J");

    System.out.println("The Array List before user input: ");
    for (String card : allCards) {
        System.out.print(card + " ");
    }
    System.out.println();
    Scanner scanner = new Scanner(System.in);
    System.out.print("Input to remove from Array List: ");
    String input = scanner.nextLine();
    allCards.remove(input);

    System.out.println("The Array List after user input: ");
    for (String card : allCards) {
        System.out.print(card + " ");
    }
    scanner.close();


0 commentaires

0
votes

Vous voulez donc être capable de lire un int code> ou un char code> de l'entrée. Je suppose que vous devrez définir une syntaxe de votre chaîne d'entrée, vous permettant de décider s'il s'agit d'un int code> ou d'un char code>. Vous pouvez utiliser une regexp pour cela.

Exemple: P>

private static final Pattern RE
        = Pattern.compile("^\\s*(?:([0-9]+)|'(.)')\\s*");

    Scanner scanner = new Scanner(System.in);
    String s = scanner.nextLine();
    Matcher matcher = RE.matcher(s);
    if (!matcher.matches()) {
        System.out.println("Bad input");
    } else {
        Object key;
        if (matcher.group(1) != null) {
            key = Integer.valueOf(matcher.group(1));
        } else {
            key = matcher.group(2).charAt(0);
        }
        allCards.remove(key);
        System.out.println(allCards);
    }


0 commentaires

0
votes

Il y a deux parties de cette question, vous devez d'abord lire correctement un caractère ou un entier, puis supprimer cela de la liste. Première ligne par ligne et convertir en Int ou en caractères, utilisez ensuite Itérateur pour boucler dans la liste et supprimer l'objet et la rupture de l'objet.

public static void main(String[] args) {
        List<Object> allCards = new ArrayList<>();
        allCards.add(2);
        allCards.add(2);
        allCards.add(3);
        allCards.add('K');
        allCards.add('J');
        Scanner scan = new Scanner(System.in);
        while (true) {
            String line = scan.nextLine();
            try {
                int num = Integer.parseInt(line);
                for(Iterator<Object> it = allCards.iterator(); it.hasNext(); ) {
                    Object o = it.next();
                    if ((o instanceof Integer) && (Integer) o == num) {
                        allCards.remove(o); break;
                    }
                }
            } catch (Exception ex) {
                char c = line.charAt(0);
                for(Iterator<Object> it = allCards.iterator(); it.hasNext(); ) {
                    Object o = it.next();
                    if ((o instanceof Character) && (Character) o == c) {
                        allCards.remove(o); break;
                    }
                }
            }
        }
    }


2 commentaires

Pourquoi iTERE au-dessus des listes et non seulement appeler supprimer (objet) ?


J'ai pensé à l'étendre à soutenir plus que des objets entier et de caractère. Étant donné que les objets.equaux vérifient à titre de référence seulement il ne fonctionnera pas correctement. Mais il s'avère des efforts inutiles qui gardent à l'esprit la question de l'OP.



0
votes

supposant que vous ne puissiez pas modifier le type de tableau AllCards code> Vous devez lancer l'entrée à la fois entier et au caractère et vérifiez si elles sont contenues dans la liste:

    final List<Card> allCards = new ArrayList<Card>();
    allCards.add(new Card(CardValue.C2));
    allCards.add(new Card(CardValue.C2));
    allCards.add(new Card(CardValue.C3));
    allCards.add(new Card(CardValue.CK));
    allCards.add(new Card(CardValue.CJ));

    playCard(allCards);

    System.out.println("The Array List after user input: ");
    for (Card card : allCards) {
        System.out.print(card.getValue() + " ");
    }

    private void playCard(List<Card> allCards) {
        final Scanner scanner = new Scanner(System.in);
        final String i = scanner.nextLine();
        scanner.close();

        final CardValue cardValue = CardValue.getCardValue(i);
        final Optional<Card> foundCard = allCards.stream().filter(c -> c.getValue() == cardValue).findAny();

        if (foundCard.isPresent()) {
            allCards.remove(foundCard.get());
        } else {
            throw new IllegalArgumentException("You have no card with value " + i);
        }

    }

    private class Card {
        private final CardValue value;

        private Card(CardValue value) {
            this.value = value;
        }

        private CardValue getValue() {
            return value;
        }

    }

    private enum CardValue {
        C2("2"),
        C3("3"),
        // all other values ...
        CJ("j"),
        CK("k");

        private final String value;

        CardValue(String value) {
            this.value = value;
        }

        public CardValue getCardValue(String value) {
            for (CardValue c : CardValue.values()) {
                if (c.value.equals(value.toLowerCase().substring(0, 1))) {
                    return c;
                }
            }
            throw new IllegalArgumentException("Illegal card value " + value);
        }
    }


0 commentaires