![](/img/trans.png)
[英]is there a way to simplify this terminal class I wrote or make it more efficient :) thnks
[英]Any way to simplify a program I wrote? (beginning programmer)
我是從大學里的Java編程(沒有編程專業背景的Comp Sci專業)開始的,在業余時間,我已經編寫了一個程序,該程序可以計算已知的2個直角三角形的缺失邊。 我實際上使用了到目前為止學到的所有技術和方法來制作該程序,我只是想知道是否有任何方法可以簡化該程序或該程序中包含的任何內容。 謝謝您的幫助。
Scanner e = new Scanner(System.in);
String hIf;
String unit;
double a;
double b;
double c;
/*The purpose of this program is to just ask for 2 sides of a right triangle to calculate the third side,
or, in other words, this program evaluates the pythagorean theorem, a^2+b^2=c^2
*/
System.out.println("This program will calculate one missing side length of a right triangle.");
System.out.println("Please input the units you will be using.");
unit = e.nextLine();
System.out.println("Will you be calculating the length of the hypotenuse? Type yes or no.");
hIf = e.nextLine();
while(!(hIf.equalsIgnoreCase("yes")||hIf.equalsIgnoreCase("no")))
{
System.out.println("Not a valid answer. Please type yes or no.");
hIf = e.nextLine();
}
if (hIf.equalsIgnoreCase("yes"))
{
System.out.println("To calculate the length of the hypotenuse, you will need to input the length of the two other sides.");
System.out.println("Please input the length of side A.");
a = e.nextDouble();
System.out.println("Please input the length of side B.");
b = e.nextDouble();
c = Math.pow(a, 2) + Math.pow(b, 2);
c = Math.sqrt(c);
}
else
{
System.out.println("To calculate the length of the missing side, you will need to input the length of the hypotenuse, and the other known side.");
System.out.println("Please input the length of the hypotenuse. Note that this is the longest possible side of the triangle.");
c = e.nextDouble();
System.out.println("Please input the length of the other side.");
a = e.nextDouble();
while(!(c>a))
{
System.out.print("The inputted hypotenuse is impossible. Note that the hypotenuse must be the longest side.");
System.out.println(" Please input the hypotenuse again.");
c = e.nextDouble();
}
b = Math.pow(c, 2) - Math.pow(a, 2);
b = Math.sqrt(b);
}
System.out.println("Side A: " + String.format("%.2f", a) + " " + unit);
System.out.println("Side B: " + String.format("%.2f", b) + " " + unit);
System.out.println("Side C: " + String.format("%.2f", c) + " " + unit);
我本人還很新,所以請服食我的鹽。 但是從美學的角度來講,我認為if和else語句中的代碼可以移至各自獨立的函數中。 另外,您可以研究使用一個基本的GUI來控制“是”輸入,以便確定一個確定的值。 我在我的一個課程中了解到,您應該盡可能避免使用字符串比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.