JOptionPane showMessageDialog用法

时间:2017-01-14 21:09:29

标签: java joptionpane messagebox

我是java的初学者。 我有一个最终成绩的项目。我做了一些事情,但我需要你的帮助。 我的项目是关于数学运算的。我应该使用JOptionPane。 我可以先处理InputDialog但我无法在消息框中显示它们(我只使用println来查看如何工作)。当然,分工部分非常重要。如果你试图除以零,它应该是错误的,应该写一些关于错误的东西。我在等你的帮助。非常感谢和最诚挚的问候。

import javax.swing.JOptionPane;

public class JavaMath3 {

    public static void main(String[] args) {

        int num1, num2, add, sub, multi;
        double div;



       num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
       num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));


        add = num1+num2;
            System.out.println("Addition " + add);

        sub = num1-num2;
            System.out.println("Subtraction " + sub);

        multi = num1*num2;
            System.out.println("Multiplication " + multi);

        if(num2 != 0 ) {
            div = (double) num1/num2;
            System.out.println("Division: " + div);
        }
        else {
            System.out.println("A number can not divided by zero.");
        }

    }

}

2 个答案:

答案 0 :(得分:0)

这是一个非常简单的你可以使用 JOPtionPane 方法 showMessageDialog

JOptionPane.showMessageDialog(parent, "your message");

这是一个示例代码

public static void main(String[] args)
{
    int num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
    int num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));
    int sum = num1 + num2;
    JOptionPane.showMessageDialog(null, "sum = " + sum);
}

更新后

这是一个完整的例子

public static void main(String[] args)
{
    int num1, num2, add, sub, multi;
    double div;

    num1 = Integer.parseInt(JOptionPane.showInputDialog("Write 1st number."));
    num2 = Integer.parseInt(JOptionPane.showInputDialog("Write 2nd number."));

    add = num1 + num2;

    sub = num1 - num2;

    multi = num1 * num2;

    String result = "sum = " + add + "\n" + "sub = " + sub + "\nmul = " + multi;
    if (num2 != 0)
    {
        div = (double) num1 / num2;
        result = result + " \n div = " + div;
    } else
    {
        result = result + " \n div = A number can not divided by zero";
        System.out.println("A number can not divided by zero.");
    }

    JOptionPane.showMessageDialog(null, result);

}

答案 1 :(得分:0)

我没有得到什么意思的框,但是如果你想要它们都在同一个对话框中,你可以在你的else声明之后写下这一行:

JOptionPane.showMessageDialog(null, "Addition: " + add+ "\nSubtraction: " + sub+"\nMultiplication " + multi+ "\nDivision: " + div);