我已经为此工作了三天,我无法解决这个问题。请帮忙!
public static void displayType (String ntype)
{
switch (ntype)
case "African":
System.out.print ("This Elephant is African")
break;
case "Indian":
System.out.print ("This Elephant is Indian")
break;
default :
System.out.print ("This type of Elephant is invalid")
return ntype;
} //End Switch
}
这些是我得到的错误:
Lab2Unit4Psuedocode.java:108: error: class, interface, or enum expected
public static void displayType (String ntype)
^
Lab2Unit4Psuedocode.java:116: error: class, interface, or enum expected
case "Indian":
^
Lab2Unit4Psuedocode.java:120: error: class, interface, or enum expected
default :
^
Lab2Unit4Psuedocode.java:124: error: class, interface, or enum expected
} //End Switch
^
4 errors
答案 0 :(得分:2)
请查看以下代码中的评论。
public class Lab2Unit4Psuedocode {
public static void displayType (String ntype) {
switch (ntype) { //you need the open curly brace
case "African":
System.out.println("This Elephant is African"); //<-- you need to terminate with semi-colons in Java
break;
case "Indian":
System.out.println("This Elephant is Indian");
break;
default:
System.out.println("This type of Elephant is invalid");
//some people add an explicit break here
//don't return anything. By definition, void means you return nothing.
}
}
} //always line up your curly braces
另请注意,在switch
数据类型上使用String
仅在Java 7中出现,因此这不适用于旧版本的Java。
Java需要大量的练习 - 坚持下去!
答案 1 :(得分:0)
public static String displayType (String ntype)
{
switch (ntype) {
// Only version 1.7 or higher can support the string literal in switch
case "African":
System.out.print ("This Elephant is African");
break;
case "Indian":
System.out.print ("This Elephant is Indian");
break;
default :
System.out.print ("This type of Elephant is invalid");
return ntype;
} //End Switch
}