使用扫描仪查找圆、三角形和矩形的面积



我对编程很陌生,我的代码有很多问题。我有两个主要问题找不到。我正在尝试一种等价的案例方法。它应该计算不同物体的面积。此外,我不知道在哪里可以找到我的in.close();

import java.util.Scanner;
class Area {
public static void main(String[] args) {
String str1 = "C";
String str2 = "c";
boolean help;
help = str1.equals( str2 );

Scanner scan = new Scanner(System.in);
System.out.println("Hello what is your name");
String name = scan.next();
System.out.println("welcome" + name );
 System.out.println("Enter c=circle t+triangle r+rectangle q=quit");
 String response = scan.next();
 if (response.equals("c") )
 {
 System.out.println("you entered the letter c");
 System.out.println("what is the radius?");
 float radius = scan.nextFloat();
 float pi = (float) 3.14f;
 System.out.print("the calculated area of the shape is ");
 System.out.println(radius* pi* radius);
 }
 else
 {
 if (response.equals("t") )
 {
 System.out.println("you entered the letter t");
 System.out.println("what is your base?");
 float base = scan.nextFloat();
 System.out.println("what is your height"); 
 float height = scan.nextFloat();
 System.out.print("the calculated area of the shape is ");
 System.out.println(base * height /2 );


  }
  else
  {
  if (response.equals("r"))
  {
  System.out.println("You entered the letter r");
  System.out.println("what is your base?"); 
  float base = scan.nextFloat();
  System.out.println("what is your height?"); 
  float height = scan.nextFloat();
  System.out.print("the calculated area of the shape is ");
  System.out.println(base * height);
  }
  else
  System.out.println("you have quit");

 }
 }}}

首先,无论大小写,都可以使用String.equalsIgnoreCase(String s)方法来比较两个字符串。例如:

String str1 = "C";
String str2 = "c";
boolean help = str1.equalsIgnoreCase(str2);

help的值将为true

此外,为了避免有很多嵌套的if... else结构,您可以使用单个if... else if... else结构,如下所示:

if (response.equalsIgnoreCase("c")) {
    // Circle
}
else if (response.equalsIgnoreCase("t")) {
    // Triangle
}
else if (response.equalsIgnoreCase("r")) {
    // Rectangle
}
else {
    // Quit
}

最后,您可以在main方法结束时关闭扫描仪,在if... else s:之后

scan.close();

最新更新