Question

hi i have this problem i got a method that let a user insert a value representing the "quantity" of a product, now if the quantity wanted by the user is higher then the stock quanity it has to throw an exception and let the user input again the number i tryed it inserting a recursive call of the same method but even if it success it goes in an infinite loop like the exception is still "alive"

...
try {
    if (!lol2)
        throw new NegativeNumberException(); 
} catch (NegativeNumberException pto) {
    JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
    this.addToCart(cart,quant);         
}

EDIT i am including now all the code but it's a bit hard so sry for the "complexity" of the code

FULL CODE

public void addToCart(ArrayList<Utilizzabile> cart,ArrayList<Integer> quant) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean lol=false;
Utilizzabile us=null;
String id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id ==null) { return;}
while (!id.matches("[0-9]+")) { //user inserts a value and the while checks for an int value inserted
    JOptionPane.showMessageDialog(frame, "Valore inserito errato");
    id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
    if (id == null) { return;} }
int iden = Integer.parseInt(id);
for (Utilizzabile u: arr) { // this for loop checks if the ID inserted represents a product in the catalog
    if ((u.getId() == iden) && (u.eAcquistabile())) {
        lol =true;
        us = u; } } 
if (lol == true) { //now if the ID corresponds to an existent product it ask the user to input the quantity requested
    boolean lol2=false;
    String qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
    if (qua ==null) { return;}
    while (lol2==false) {
    while (!qua.matches("[0-9]+")) {
        JOptionPane.showMessageDialog(frame, "Valore inserito errato");
        qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
        if (qua == null) { return;} }
    if (qua.length()>0 && qua.length()<=8) {
    int quantit = Integer.parseInt(qua);
    for (int l=0;l<cart.size();l++) { //this for checks if in the cart were already that product and then changes the quantities only
        if ((cart.get(l).getId() == us.getId()) && (us.getRem()-quantit >0) ) {
            int num = quant.get(l)+quantit;
            quant.set(l,num);
            JOptionPane.showMessageDialog(frame, "Quantità del prodotto richiesto aggiornata");
            return;}                
    }
    if ( (us.getRem()-quantit) >0) { //checks if all went good and the quantity is avaiable
            JOptionPane.showMessageDialog(frame, "Prodotto della quantità richiesta aggiunto al carrello");
            lol2=true;
            cart.add(us);
            quant.add(quantit);} }
    try {
        if (lol2==false)
            throw new NegativeNumberException(); }
    catch (NegativeNumberException pto){
        JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
        this.addToCart(cart,quant); }       
    } }
else {
    JOptionPane.showMessageDialog(frame, "Prodotto non trovato");
    this.addToCart(cart,quant); }       

}

this code essentially is a graphical section for let the user add a product to the cart and check is everything is good but i need to place an exception to check if the quantity in stock is less then the quantity wanted by the user (i ve done it without exception with no problems but this is for an exam and i just noticed that the professor wants that i have to solve this problem by using an exception

Was it helpful?

Solution

It's not good to use recursion for that, because after "n" invocations you can receive StackOverFlowError. And I agree with @laune. Thus I recommend to use loop. For example:

while (true){
    // lol2 here is TRUE if was entered correct value and false if not.
    if (lol2)
        break;
    else {
        JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
        this.addToCart(cart,quant);
    }
}

OTHER TIPS

insert try catch into do while loop.

when user insert correct value stop loop E.g

  int a=10;
  do{
        try{
             if(a<20)   
                 throw new NegativeNumberException(); 
             else
                  break;
           }catch (NegativeNumberException pto){

              JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
              //enter quantity again
              // a=20;
           }
    }while(true);

Never use exceptions to control the regular or almost regular flow of control. It's bad programming style.

Use some do statement to repeat the dialog until a satisfactory input is achieved.

Due to lack of context, no code is provided. (Where is that recursive call??)

Later There is room for exception handling, though. You could throw away pattern matching and length check and catch NumberFormatException.

Integer quantity = null;
do {
    String id ... dialogue
    try {
        quantity = Integer.parseInt( id );
        if( quantity <= 0 ) throw new NumberFormatException( "only positive integers" );
    } catch(  NumberFormatException nfe ){
        ... error dialogue;
        quantity = null;
    }
} until( quantity != null );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top