我正在尝试使用此公式查找区域,但是,变量a,b和c未初始化。如何初始化它们并让它们与扫描仪一起使用?
import java.text.DecimalFormat;
import java.util.Scanner;
public class PA2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.##");
float a, b, c;
float s = (a + b + c);
float pt1, pt2, pt3, pt4, pt5, pt6;
double Area;
pt1 = (s - a);
pt2 = (s - b);
pt3 = (s - c);
pt4 = (s * pt1);
pt5 = (pt4 * pt2);
pt6 = (pt5 * pt3);
Area = Math.sqrt(pt6);
System.out.println("Enter first side: ");
a = scan.nextFloat();
System.out.println("Enter second side: ");
b = scan.nextFloat();
System.out.println("Enter third side: ");
c = scan.nextFloat();
System.out.println("Your area is: " + fmt.format(Area));
}
}
答案 0 :(得分:1)
在开始编写代码之前,在文章中定义顺序和算法是一个好习惯......
你的方法并不是那么糟糕,只需在代码中订购序列:
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.##");
//1. delcare the variables and initialize it...
float a = 0f;
float b = 0f;
float c = 0f;
//2. get the input
System.out.println("Enter first side: ");
a = scan.nextFloat();
System.out.println("Enter second side: ");
b = scan.nextFloat();
System.out.println("Enter third side: ");
c = scan.nextFloat();
//3. Do the Math behind the scenes
float s = (a + b + c);
float pt1, pt2, pt3, pt4, pt5, pt6;
double Area;
pt1 = (s - a);
pt2 = (s - b);
pt3 = (s - c);
pt4 = (s * pt1);
pt5 = (pt4 * pt2);
pt6 = (pt5 * pt3);
Area = Math.sqrt(pt6);
//4. Print the results....
System.out.println("Your area is: " + fmt.format(Area));
答案 1 :(得分:0)
只需这样做,而不仅仅是
float a, b, c;
它的:
float a=0;
float b=0;
float c=0;
初始化变量。我和另一个程序有同样的问题。希望这会有所帮助。