Search code examples
javastringif-statementjoptionpanejcreator

How do i input an If statement on to my program using JOption.pane?


Hi i'm a newbie at programming, i'm having a bit of a trouble by adding an IF statement on to my program. I'm creating a Module Result calculator, the user inputs their result score for their exam and coursework, if the user achieves of 40% the program replies with "Well done you've passed!" and if they get below 40% it replies back saying "Sorry but you failed!" however I've got the program to calculate the score but the message doesn't show on the GUI. ![enter image description here][1] I've created another one which is success, it shows the outcome on the console instead of the GUI.

I would appreciate it if someone could help me with the codes in this situation.

class GUI{
public static void main(String[] args) {

        String result1 = JOptionPane.showInputDialog("Enter Coursework Result:");
        String result2 = JOptionPane.showInputDialog("Enter Exam Result:");


        int num1 = Integer.parseInt(result1);
        int num2 = Integer.parseInt(result2);
        int avg =  (num1 + num2)/2;

        if (avg<40)
           System.out.println("Your Test Score:  "+avg+"% Sorry But You Failed!");
        else if(avg<=100)
           System.out.println("Your Test Score:  "+avg+"% Well Done, You Passed!");
}
}

Solution

  • You need to store your resulting message in a String:

    String message = "";
    if (avg<40)
        message = "Your Test Score:  "+avg+"% Sorry But You Failed!";
    
    else if(avg<=100)
        message = "Your Test Score:  "+avg+"% Well Done, You Passed!";  
    

    Then you can display it using a JOptionPane using the following:

    JOptionPane.showMessageDialog(null, message);
    

    What you are currently doing is printing out the result to the console using System.out.println(). This will not print it out to the GUI. The JOptionPane.showMessageDialog() method will display a dialog box with your resulting message.