输入/输出 - 算术方程

时间:2015-05-20 18:52:04

标签: java swing input output

我是Java的新手,两周前就已经开始了,我遇到了围绕这个问题的问题。我在上课时提出的课程中遇到了问题。将千克转换为磅并舍入到小数点后第二位。

我可以创建事物的输入端并打开一个对话框来提示用户输入权重。我还可以创建一个输出,使用我在一个对话框中输出答案的公式。

我的问题是如何获取输入的信息并使用它将公斤转换为磅?

我一直在读我的书,在互联网上寻找答案,我想我可能已经在思考了。谢谢你的帮助。

Input.java

//This program asks a user to input a weight in kilograms.

package module2;

import javax.swing.*;

public class Input {

    public static void main(String[] args) {

        String weight;

        weight = JOptionPane.showInputDialog("Enter weight in kilograms");
    }
}

Output.java

//This program outputs a converted weight from kilograms to pounds.

package module2;

import javax.swing.JOptionPane;

public class Output {

    public static void main(String[] args) {

        double kg = 75.5;
        double lb = 2.2;
        double sum;

        sum = (kg * lb);

        JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
    }
}

2 个答案:

答案 0 :(得分:6)

现在你有两种主要方法。这两个都是该计划的切入点。由于他们必须共享信息,因此您同时拥有这些信息并不合理。

我建议将Output的主要方法更改为实例方法,并使用一个参数:来自weight的{​​{1}}。< / p>

像这样:

Input

然后,你可以从public void printOutput(final double weight){ //... } 的主要方法中调用它,如下所示:

Input

另一件事是,由于public static void main(String[] args) { String weight; weight = JOptionPane.showInputDialog("Enter weight in kilograms"); double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number Output output = new Output(); // Create a new instance of the Output class output.printOutput(kg); // Call our method to display the output of the conversion } 目前仅用于该方法,因此您可以考虑将该方法移至Output

答案 1 :(得分:0)

// addition of two integers using JOptionPane
import javax.swing.JOptionPane; 

public class Addition

{

   public static void main(String[] args)

  {

    String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
    String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
    int num1 = Integer.parseInt(firstNumber);
    int num2 = Integer.parseInt(secondNumber);
    int sum = num1 + num2;
    JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
  }
}