Home > Software design >  How to check if an ArrayList of 1D Arrays (EX : int [ ] order = new int [2] ) has a value in index 0
How to check if an ArrayList of 1D Arrays (EX : int [ ] order = new int [2] ) has a value in index 0

Time:12-13

I'm a student in my 1st year, and I need to check if an arrayList of 1D array has a value in index 0, if so I need to keep that value of index 0, and update its value of order [0,1]. So I first created my 1D array as

int [] Order = new int [2];

is a getOrder() method. Asking the user (Server in this case) to add integers (id of product) and second time to add number of how many products.

and add : Order = {idConso, nbrConso}

Then I call the method from my main(), and passing an arrayList (ord) as a parameter to store the Orders.

But, when I print the ord (arrayList of 1D Order array), I shouldn't have the same idConso twice in it.

This means I need to find a way to check if the idConso (id of the product) is already in ord (arrayList) and if so, I need to check if the arrayList has already idConso and keep it, but add the nbrConso (numnbre of orders of that product).

package testes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class test_EX_24V1 {

    final static String NAMES[] = 
        {
                "Spa reine 25 ","Bru plate 50","Bru pét 50","Pepsi","Spa orange",
                "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche","Jus d'orange Looza", "Cécémel", 
                "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ","Lait Russe ","Thé et infusions",
                "Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud","Passione Italiano","Amour Intense",
                "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25","Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ",
                "Brasse-Temps Cerises 25","Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
                "Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara","Penne poulet baslc ",
                "Tagl American","Tagl saum"
        };

    public static String getUserIntOrSpecificInputV2(String msg, String expectedAnsw, int min, int max) 
{

        int intInput = 0;
        String strAnsw = "";
        Scanner sc= new Scanner (System.in);
        do {

            System.out.println(msg);

            if (sc.hasNextInt()==true) {   //si saisie d’un entier
                intInput = sc.nextInt();//récupération de la saisie au format entier
                if (intInput >= min && intInput <= max) {
                    return Integer.toString(intInput);

                }else {
                    System.out.println("La saisie doit être comprise entre "   min    " et "   max);
                }

            } else {  //si saisie d'un texte par l’utilisateur
                strAnsw = sc.next(); //récupération de la saisie au format chaine

                if (strAnsw.length() == 1 && expectedAnsw.toUpperCase().contains(strAnsw.toUpperCase())){
                    return strAnsw.toUpperCase();

                }else {
                    System.out.println ("Erreur de saisie : caractères autorisés "    expectedAnsw );
                }
            }
        } while (true);

    }//end getUserIntOrSpecificInputV2

    public static boolean checkTable( int[] table, int numberCheck ) {

        int i = 0;

        while (i < table.length) {

            if (table[i] == numberCheck) {

                return true;

            }

            i  ;

        }

        return false;

    }//fin check Table

    @SuppressWarnings("unlikely-arg-type")
    public static void getOrder ( ArrayList<int[]> ord ) {
        //variables
        String UserInput;
        int idConso = 0, nbrConso = 0;
        int [] Order = new int [2];

        //instructions
        
        UserInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable "
                  "ou Q(Quitter) ", "Q", 1, NAMES.length);

        do {    
            
            if ( UserInput.equalsIgnoreCase( "Q" ) ) // fin de programme
            {
                System.out.println( "Fin de Programme, Au Revoir" );
                System.exit( -1 );
            }
            else 
            {
                idConso = Integer.parseInt ( UserInput );
            }

            UserInput = getUserIntOrSpecificInputV2("Nombre de consommations pour "   NAMES [ idConso -1 ]  " ? /A(Annuler) /Q (Quitter)", "AQ", 1, 5000);

            if ( UserInput.equalsIgnoreCase("Q") )
            { //fermer l'application
                System.out.println( "Fin de Programme, Au Revoir" );
                System.exit(-1);            
            }
            else if ( UserInput.equalsIgnoreCase("A") )
            { 
                //DO NOTHING !
            } 
            nbrConso = Integer.parseInt ( UserInput );
            
            Order [ 0 ] = idConso ;
            Order [ 1 ] = nbrConso ;
            
//          System.out.println("isCondo = "   idConso   " ,et nbrConso = "   nbrConso);
//          System.out.println("taille de arrayList ord = "   ord.size());

            if (ord.isEmpty()) 
            {       
                System.out.println("YES ITS EMPTY");
                ord.add(Order);
                System.out.println("added");
            }

            else 
            {
                Integer [] OrderLine = new Integer [ord.size()];
                OrderLine = ord.toArray(OrderLine);
                
                if (ord.contains(Order[0] == idConso) && Order[0] == idConso) {
                    System.out.println("containe ");
                    Order[1]  = nbrConso; 
                }
                
                ord.add(Order);
                System.out.println("added");

            }
            
            UserInput = getUserIntOrSpecificInputV2("Entrez le N° de consommable ou Q(Quitter) V (Valider le ticket) ", "QV",1, NAMES.length);

        } while (!UserInput.equalsIgnoreCase("V"));

        
        
        for ( int[] is : ord )
        {
            
            System.out.print(Arrays.toString(is));

        }
        System.out.println();
        System.out.println("Nombre de consommation : "   ord.size());
        
    }
    public static void main(String[] args) {
        //variables 
        ArrayList <int [] > order = new ArrayList<int[]>();

        getOrder(order);
        
    }

}

CodePudding user response:

You try to find an already added idConso with ord.contains(Order[0] == idConso) && Order[0] == idConso but this don't work.

Some lines above you set Order [ 0 ] = idConso so Order[0] == idConso will always be true. But ord holds int[] so ord.contains(/*Order[0] == idConso*/ true) will always be false. So && Order[0] == idConso will never be executed (even this part would always be true).

You have to iterate over all added orders and check the ID. If you found the ID you have to increase the corresponding nbrConso but not add the order again (you do so even you find the entry). With a for-loop it may look like

// flag if idConso was found in ord
boolean containe = false;
for (int[] added : ord) {
    if (added[0] == idConso) {
        // found it
        System.out.println("containe ");
        added[1]  = nbrConso;
        // set the flag
        containe = true;
        // no need to check next entries in ord
        break;
    }
}
// add only if not found
if (!containe) {
    ord.add(Order);
    System.out.println("added");
}

EDIT: due to your comment I ran the code and got two problems:

  1. I don't understand your intension of
Integer[] OrderLine = new Integer[ord.size()];
OrderLine = ord.toArray(OrderLine);

but I get an exception here. Because OrderLine is never used I removed these lines.

  1. Order is declared outside the loop so even for the second order you operate on this object. You also add this object to ord so by modify Order you also modify the list's value. You have to move int[] Order = new int[2]; into the loop to always have a new object (e. g. just before setting the values Order[0] = idConso; and Order[1] = nbrConso;)
  • Related