简体   繁体   中英

JOptionPane display message

I have question about JOptionPane. I was given an assignment to do the summation of odd number and even number. My profesor want us to diplay the "my name, the summation of odd and even number" in one JOptionPane box output. The dialog box are not allowed to prompt user to enter number.

i only know how to display my name on the dialog box. here is what i write.

import javax.swing.JOptionPane;

//class name
public class Loops
{
    //main method begin the execution of Java application
    public static void main ( String[] args )
    {
            //intialize the integer variable
        int sumOdd;
        int sumEven;
        int oddNumber;
        int evenNumber;

        sumOdd = 0;
        sumEven = 0;
        oddNumber = 1;
        evenNumber = 2;

        //create a conditional statement for integer odd number
        while ( oddNumber <=25 )    
        {
      sumOdd += oddNumber;
      oddNumber +=2;
        }   

        System.out.printf ("The sum of odd number is %d\n", sumOdd);    
        //create a conditional statement for integer even number

        while ( evenNumber <= 50 )
        {
      sumEven += evenNumber; 
      evenNumber +=2;
        }

        System.out.printf ("The sum of even number is %d", sumEven); 

        String message = "Written by BlaBla";

        JOptionPane.showMessageDialog(null, message);
    }
}

before i wrote

JOptionPane.showMessageDialog( null, "The sum of odd number is %d", The sum of even number i %d", oddNumber, evenNumber );

and i also try another combination but it wont work

any idea how to do it?

Thank you so much in advanced for helping me out.

import javax.swing.JOptionPane;

//class name

public class Loops {

//main method begin the execution of Java application
public static void main(String[] args) {
    //intialize the integer variable
    int sumOdd;
    int sumEven;
    int oddNumber;
    int evenNumber;

    sumOdd = 0;
    sumEven = 0;
    oddNumber = 1;
    evenNumber = 2;

    //create a conditional statement for integer odd number
    while (oddNumber <= 25) {
        sumOdd += oddNumber;
        oddNumber += 2;
    }

    String str = "The sum of odd number is =" + sumOdd;
    JOptionPane.showMessageDialog(null, str);
    while (evenNumber <= 50) {
        sumEven += evenNumber;
        evenNumber += 2;
    }

     str = "The sum of even number is =" + sumEven;
    JOptionPane.showMessageDialog(null, str);
    String message = "Written by BlaBla";

    JOptionPane.showMessageDialog(null, message);
}

}

Use String.format :

JOptionPane.showMessageDialog( null, 
   String.format("The sum of odd number is %d, The sum of even number i %d", 
       oddNumber, evenNumber ));

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM