2014-09-12 65 views
0

我对编程非常陌生,而且我的代码有很多问题。我有两个主要的问题,我真的找不到。我正在尝试使用equalsignorecase方法。它应该计算不同对象的面积。另外我不知道在哪里有我的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"); 


} 
}}} 
+0

请添加[Java]标签,以便我们可以使用语法高亮。此外,你会改善某人看你的问题的变化。 – 2014-09-12 21:37:11

回答

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 s:

scan.close();