Java 调用静态方法
为什么这段代码显示编译错误void对于变量测试是无效类型Java 调用静态方法,java,static-methods,Java,Static Methods,为什么这段代码显示编译错误void对于变量测试是无效类型 public class Tester{ public static void main(String[] args){ static void test(String str){ if (str == null | str.length() == 0) { System.out.println("String is empty"); }
public class Tester{
public static void main(String[] args){
static void test(String str){
if (str == null | str.length() == 0) {
System.out.println("String is empty");
}
else {
System.out.println("String is not empty");
}}
test(null);
不能在另一个方法中声明方法。将
测试从main
推迟。您也不能从类中调用方法<代码>测试(空)代码>必须位于方法内部,例如main。
public class Tester{
public static void main(String[] args){
test(null);
}
static void test(String str){
if (str == null | str.length() == 0) {
System.out.println("String is empty");
}
else {
System.out.println("String is not empty");
}
}
您试图在另一个方法(main
)中声明一个方法(test
)。不要那样做。将test()
直接移动到类中:
public class Tester{
public static void main(String[] args) {
test(null);
}
static void test(String str) {
if (str == null | str.length() == 0) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
}
}
(请注意,我还修复了缩进和空格。您可以使用各种约定,但您应该保持一致,并且比问题中的代码更清晰。)您的方法测试在另一个方法中
把测试方法放在你的主要测试之外
public class Tester{
public static void test(String str){
if (str == null || str.length() == 0) {
System.out.println("String is empty");
}
else {
System.out.println("String is not empty");
}
}
public static void main(String[] args){
test(null);
}
}
您还必须添加双精度或操作数(| |),以便在没有空指针异常错误的情况下正常工作。您正在main方法中声明测试方法。因此,将测试方法与主要测试方法分开
public class Tester
{
public static void test(String str)
{
if (str == null || str.length() == 0)
{
System.out.println("String is empty");
}
else
{
System.out.println("String is not empty");
}
}
public static void main(String[] args)
{
test(null);
}
}
谢谢,澄清了概念和代码约定将您的test
方法移出main
方法不要将字符串与==,而要与.equals()进行比较。字符串是对象,如果要比较所需对象的值,请使用.equals(),否则将比较引用。如果其中一个操作数为null==works,则应使用它,因为如果str为null,str.equals(null)将抛出NullPointerException-1进行注释