当我尝试运行它时,代码给出了一个布尔错误。它说布尔值不能用静态来解决。可能是什么答案。?
package csd;
class Uti {
public static void main(String[] args) {
boolean result;
result = Sample.foo() && Sample.bar();
System.out.printf("result%b%n",result);
}
class Sample {
public static boolean foo() {
System.out.println("foo");
return true;
}
public static boolean bar() {
System.out.println("bar");
return false;
}
}
}
错误讯息:
线程“main”中的异常java.lang.Error:未解决的编译问题:方法foo不能声明为static;静态方法只能在静态或顶级类型中声明
答案 0 :(得分:4)
将Sample
类设为静态将解决您的错误:
class Uti {
public static void main(String[] args)
{
boolean result;
result = Sample.foo() && Sample.bar();
System.out.printf("result%b%n",result);
}
static class Sample {
public static boolean foo() {
System.out.println("foo");
return true;
}
public static boolean bar()
{
System.out.println("bar");
return false;
}
}
}
使它成为顶级课程也将有效:
class Sample {
public static boolean foo() {
System.out.println("foo");
return true;
}
public static boolean bar()
{
System.out.println("bar");
return false;
}
}
class Uti {
public static void main(String[] args)
{
boolean result;
result = Sample.foo() && Sample.bar();
System.out.printf("result%b%n",result);
}
}
答案 1 :(得分:1)
您的代码中存在编译错误,您可以通过在代码中向父类型添加静态修饰符来解决您的问题:
public static void main(String[] args)
{
boolean result;
result = Sample.foo() && Sample.bar();
System.out.printf("result%b%n",result);
}
static class Sample {
public static boolean foo() {
System.out.println("foo");
return true;
}
public static boolean bar()
{
System.out.println("bar");
return false;
}
}