frequent_sleeper
frequent_sleeper

Reputation: 93

How to add multiple if loop results to a single JOptionPane message dialog?

I'm super new to all of this but I'm trying to figure out how to get all the following results (which are now shown in separate message dialogs following each other) into a single message dialog window.

JOptionPane.showMessageDialog(null, "De prijs per persoon is  €" + part + ".");

    if (fnum > part){
        JOptionPane.showMessageDialog(null, fname + " krijgt  €" + (fnum - part) + " terug.");
    }
    else if (fnum < part) {
        JOptionPane.showMessageDialog(null, fname + " moet nog  €" + (part - fnum) + " betalen.");
    }
    else {
        JOptionPane.showMessageDialog(null, fname + " heeft alles betaald.");
    }


    if (snum > part){
        JOptionPane.showMessageDialog(null, sname + " krijgt  €" + (snum - part) + " terug.");
    }
    else if (snum < part) {
        JOptionPane.showMessageDialog(null, sname + " moet nog  €" + (part - snum) + " betalen.");
    }
    else {
        JOptionPane.showMessageDialog(null, sname + " heeft alles betaald.");
    }


    if (tnum > part){
        JOptionPane.showMessageDialog(null, tname + " krijgt  €" + (tnum - part) + " terug.");
    }
    else if (tnum < part) {
        JOptionPane.showMessageDialog(null, tname + " moet nog  €" + (part - tnum) + " betalen.");
    }
    else {
        JOptionPane.showMessageDialog(null, tname + " heeft alles betaald.");
    }

Upvotes: 1

Views: 896

Answers (1)

takendarkk
takendarkk

Reputation: 3445

Instead of creating a JOptionPane inside of each if statement, you only need a single one at the end. Your if statements are really only determining what string to display, so that's the only info you need to create inside them. You can do this by creating a string variable and determining what it contains in the if statements. Then, once your statements have executed, you create a single JOptionPane with your string included. For example:

String temp;

if (fnum > part) {
    temp = fname + " krijgt  €" + (fnum - part) + " terug.";
}
else if (fnum < part) {
    temp = fname + " moet nog  €" + (part - fnum) + " betalen.";
}
else {
    temp = fname + " heeft alles betaald.";
}

JOptionPane.showMessageDialog(null, temp);

As per your comments - If you want strings to be placed on multiple lines you can add a "\n" character to your string anywhere you want it to move to a new line.

Upvotes: 2

Related Questions