JOptionPane显示消息

时间:2014-09-26 10:59:41

标签: java joptionpane

我对JOptionPane有疑问。 我被赋予一个任务来做奇数和偶数的总和。 我的教授希望我们在一个JOptionPane框输出中显示“我的名字,奇数和偶数的总和”。不允许该对话框提示用户输入数字。

我只知道如何在对话框中显示我的名字。 这是我写的。

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);
    }
}
在我写

之前

JOptionPane.showMessageDialog(null,“奇数之和为%d”,偶数i%d“,oddNumber,evenNumber之和);

我也尝试了另一种组合,但它不会起作用

任何想法怎么做?

非常感谢您提前帮助我。

2 个答案:

答案 0 :(得分:1)

导入javax.swing.JOptionPane;

//班级名称

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);
}

}

答案 1 :(得分:0)

使用String.format

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