1. 程式人生 > >求知若飢, 虛心若愚。

求知若飢, 虛心若愚。

根據3個實數構造一個三角形物件,要求3個實數若不滿足三角形構成條件則自動以最小值為邊構造等邊三角形,求構造出的三角形的面積。

import javax.swing.JOptionPane;

public class Triangle {
	private double ed1, ed2, ed3;
	
	public Triangle() {
		this.ed1 = 0;
		this.ed2 = 0;
		this.ed3 = 0;
	}
	public Triangle(double e1, double e2, double e3) {
		this.ed1 = e1;
		this.ed2 = e2;
		this.ed3 = e3;
	}
	public Triangle Judge(Triangle t) {
		double sum1, sum2, sum3, area, s, min;
		sum1 = this.ed1 + this.ed2;
		sum2 = this.ed1 + this.ed3;
		sum3 = this.ed2 + this.ed3;
		s = (this.ed1 + this.ed2 + this.ed3) / 2;
		area = Math.sqrt(s * (s - this.ed1) * (s - this.ed2) * (s - this.ed3));
		
		if (this.ed1 < 0 | this.ed2 < 0 | this.ed3 < 0)
			System.out.println("輸入有誤,此三角形不存在!");
		else {
			if (sum1 > this.ed3 & sum2 > this.ed2 & sum3 > this.ed1) 	
				System.out.println("三角形的面積為:" + area);
			else {
				min = Math.min(Math.min(this.ed1, this.ed2), Math.min(this.ed2, this.ed3));
				s = (min * 3) / 2;
				area = Math.sqrt(s * Math.cbrt(s - min));
				
				System.out.println("輸入有誤,此三角形不存在!");
				System.out.println("自動構造以最小值為邊的等邊三角形!");
				System.out.println("三角形的面積為:" + area);
				}
		}
		return this;
	}
	
	public static void main(String[] args) {
		String str1 = JOptionPane.showInputDialog("請輸入三角形的第一條邊:");
		String str2 = JOptionPane.showInputDialog("請輸入三角形的第二條邊:");
		String str3 = JOptionPane.showInputDialog("請輸入三角形的第三條邊:");
		
		double e1, e2, e3;
		e1 = Double.valueOf(str1);
		e2 = Double.valueOf(str2);
		e3 = Double.valueOf(str3);
		
		Triangle triangle = new Triangle(e1, e2, e3);
		triangle.Judge(triangle);
	}
}

Java標準輸入框:需要匯入相應的包和類。

String str1 = JOptionPane.showInputDialog(message); 

String 型別轉換為double 型別:

double e3 = Double.valueOf(str3);