我用Java编写了一个程序,用Heron的公式计算三角形的面积。
使用NetBeans编写,源代码中设置三角形的边:
public class TriangleArea {
public static void main(String[] args) {
double side1=6;
double side2=8;
double side3=10;
double s = (side1 + side2 + side3) / 2;
double area = Math.sqrt(s * (s - side1) * (s - side2 ) * (s - side3));
System.out.println("area of the triangle is " + area);
}
}
如何将其转换为可运行程序,询问用户三角形边并可双击运行?
答案 0 :(得分:0)
要允许用户更改参数,您可以要求用户使用JOptionPane输入它们,您也可以使用它来显示消息:
public class TriangleArea {
public static void main(String[] args) {
double side1 = getDouble("Length of the first side");
double side2 = getDouble("Length of the second side");
double side3 = getDouble("Length of the third side");
double s = (side1 + side2 + side3) / 2;
double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
JOptionPane.showMessageDialog(null, "area of the triangle is " + area);
}
/**
* Ask the user to input a double. Will continue asking until a valid double is input.
* @param message
* @return
*/
public static double getDouble(String message) {
while(true) {
try {
return Double.parseDouble(JOptionPane.showInputDialog(message));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "That is not a valid number, try again");
}
}
}
}
要允许用户通过在Windows中双击它来运行它,您可以从中构建JAR文件。我不熟悉Netbeans,但根据this answer关于如何做到这一点的问题,您可以在以下情况下启用它:
Project Properties -> Build -> Packaging -> Build JAR after compiling
JAR应该在您构建时在项目中显示一些内容。请注意,它将要求您的用户使用相同版本或晚于您使用的Java的工作安装。