Home > Software engineering >  Nested If-Else Statements
Nested If-Else Statements

Time:08-12

The code below is self explanatory. Everything works fine. (cb1 and cb2 are combo boxes).

HashMap<String,String> map = new HashMap<>();
ArrayList eight_to_nine = new ArrayList<>();
ArrayList nine_to_ten = new ArrayList<>();

private void btnActionPerformed(java.awt.event.ActionEvent evt) {

int time = cb1.getSelectedIndex();
String name = (String)cb2.getSelectedItem();
String a = map.get(name);

        
        if (time==0 && (!eight_to_nine.contains(name) || !eight_to_nine.contains(a))) {
            Collections.addAll(eight_to_nine, name, a);
            System.out.println("eight to nine: "   eight_to_nine);

        } else if (time==1 && (!nine_to_ten.contains(name) || !nine_to_ten.contains(a))){
            Collections.addAll(nine_to_ten, name, a);
            System.out.println("nine to ten: "   nine_to_ten);

        } else {
            JOptionPane.showMessageDialog(null, "Clash Detected!", "Error", JOptionPane.ERROR_MESSAGE);
        }
}

However, I want to add one more condition, which is each arraylist must not contain more than 5 elements. Something like:

if(eight_to_nine.size()>5 || nine_to_ten.size()>5) {
           JOptionPane.showMessageDialog(null, "Maximum Capacity Reached!", "Error", JOptionPane.ERROR_MESSAGE);
       }

But I am unsure where should I put this line. I want the error to pop up without the arraylist being printed. And I am also unsure if I should use nested if-else or put everything in a While loop. Any suggestions?

CodePudding user response:

With a bit of refactoring this is just one approach (may be affected by question in comments):

private void btnActionPerformed(java.awt.event.ActionEvent evt) {
    
    //...existing code
    
    if (time == 0 && isUniqueTo(eight_to_nine,name,a)) {
        if (hasRoom(eight_to_nine,5)) {
            Collections.addAll(eight_to_nine, name, a);
            System.out.println("eight to nine: "   eight_to_nine);
        }
    }

    else if (time == 1 && isUniqueTo(nine_to_ten,name,a)) {
        if (hasRoom(nine_to_ten,5)) {
            Collections.addAll(nine_to_ten, name, a);
            System.out.println("nine to ten: "   nine_to_ten);
        }
    }

    else {
        JOptionPane.showMessageDialog(null, "Clash Detected!", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

private boolean isUniqueTo(ArrayList al, String name, String a) {
    return !al.contains(name) && !contains(a)
}

private boolean hasRoom(ArrayList al, int max) {
    boolean result = (al.size() < max);
    if (al.size() == max) {
        JOptionPane.showMessageDialog(null, "Maximum Capacity Reached!", "Error", JOptionPane.ERROR_MESSAGE);   
    }
    return result;
        
}

CodePudding user response:

i guess you can use a do while loop. like

enter image description here

  • Related