您好,我正在爲我的計算機科學課程編寫一個程序。目標是製作一個計算畢達哥拉斯定理的計算器。我已經做了一些研究,以瞭解我需要用什麼來循環。像while和do-while語句一樣,但我無法弄清楚如何實現它們。我試過了,我的代碼中有一些證據表明我的嘗試被註釋掉了。我如何去做循環?如何在Java中創建循環
我的代碼:
import java.util.Scanner;
public class Pythagorean_Theorem
{
public static void main(String[] args)
{
// established scanner
Scanner Toby = new Scanner (System.in);
// Declares variables
double Leg1;
double Leg2;
double Hypotenuse;
double choice;
//double num1
//double num2
//double answer
//boolean False;
// Beginning of program offering choice for calculations
System.out.println ("This program is a basic calculator that also knows the Pythagorean theorem");
System.out.println ("This program can solve for the hypotenuse or one of the legs \nOr you can use it as a simple calculator");
System.out.println ("Are you solving for the hypotenuse or a leg?");
System.out.println ("1 for hypotenuse \n2 for leg");
choice = Toby.nextDouble();
//Begins else if statements
//What you enter above corresponds to the choices below
//while ((Toby.nextDouble() != 1);
//while ((Toby.nextDouble() != 2);
{
if (choice == 1)
{
// Finding hypotenuse
System.out.println ("Enter first leg:");
Leg1 = Toby.nextDouble();
System.out.println ("Enter second leg:");
Leg2 = Toby.nextDouble();
Hypotenuse = Leg1 * Leg1 + Leg2 * Leg2;
System.out.println (Math.sqrt(Hypotenuse));
}
else if (choice == 2)
{
// Finding leg
System.out.println ("Enter the leg:");
Leg1 = Toby.nextDouble();
System.out.println ("Enter hypotenuse");
Hypotenuse = Toby.nextDouble();
Leg2 = (Hypotenuse * Hypotenuse - Leg1 * Leg1);
System.out.println (Math.sqrt(Leg2));
}
// Below here is invalid choices
else if (choice <= 0)
{
System.out.println ("This is not a valid choice");
}
else if (choice >= 3)
{
System.out.println ("This is not a valid choice");
}
}
}
}
我不我認爲在這種情況下你甚至有一個循環的理由。 – Jim
爲什麼你在'while'循環中添加分號?他們覺得他們做什麼? – Tom
@Jim原因顯然是重新運行,如果輸入無效 – ControlAltDel