JOptionPane的替代品?

时间:2014-09-18 20:36:07

标签: java joptionpane

它有效,但我需要替代JOptionPane。这是家庭作业,我们不允许使用JOptionPane。这就是我所拥有的,有效的,它不是指导者想要的。

import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class calc extends JApplet {

    double sum;
    double product;
    double difference;
    double quotient;

    public void init() {
        String firstNumber = JOptionPane.showInputDialog("Enter the first number");
        String secondNumber = JOptionPane.showInputDialog("Enter the second number");
        String thirdNumber = JOptionPane.showInputDialog("Enter the third number");
        double number1 = Double.parseDouble(firstNumber);
        double number2 = Double.parseDouble(secondNumber);
        double number3 = Double.parseDouble(thirdNumber);
        sum = number1 + number2 + number3;
        product = number1 * number2 * number3;
        difference = number1 - number2 - number3;
        quotient = number1 % number2 % number3;
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawRect(15, 10, 270, 60);
        g.drawString("Sum "+sum, 25, 25);
        g.drawString("Product "+product, 25, 35);
        g.drawString("Difference "+difference, 25, 45);
        g.drawString("Quotient "+quotient, 25, 55);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用扫描程序方法并将变量初始化为双精度数,这样您就不需要不必要地解析字符串。尝试这样的事情:

public void init() {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the first number");        
        double number1 = input.nextDouble();

        System.out.println("Enter the second number");
        double number2 = input.nextDouble();

        System.out.println("Enter the third number");
        double number3 = input.nextDouble();

        sum = number1 + number2 + number3;
        product = number1 * number2 * number3;
        difference = number1 - number2 - number3;
        quotient = number1 % number2 % number3;
    }

然后在不使用JOptionPane的情况下显示,您将使用与此类似的行:

System.out.println("Quotient is " + quotient);

请记得在必要时导入!

import java.util.Scanner;

关于作业的一些额外的清晰度将使这个问题更容易回答,但这是我根据可用信息的最佳猜测。我认为你的老师不允许你使用JOptionPane的唯一原因是因为它还没有涵盖在课程中,而且由于JOptionPane在大多数计算机科学课程中相对较早地教授,我猜想扫描仪方法很可能是你老师正在寻找的。如果您已经介绍过Scanner方法,请尝试查看InputStreamReader方法。希望这会有所帮助;)