使用扫描仪查找圆形,三角形和矩形区域

时间:2014-09-12 21:32:37

标签: java geometry area

我对编程非常陌生并且我的代码存在很多问题。我有两个主要问题,我无法找到。我试图有一个equalsignorecasemethod.It应该计算不同对象的面积。我也不知道在哪里有我的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");


 }
 }}}

1 个答案:

答案 0 :(得分:0)

首先,无论如何,您都可以使用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方法结束时关闭扫描仪:

scan.close();