Java求素数时出现错误

时间:2023-03-08 22:01:31

Java求素数时出现错误

1、具体错误如下

No enclosing instance of type Prime is accessible. Must qualify the allocation with an enclosing instance of type Prime (e.g. x.new A() where x is an instance
 of Prime).

2、错误原因

class PrimNumber
	{
		public boolean isPrim(int a)
		{
			for(int i=1;i<a/2;i++)
				if(a%i == 0)
					return false;
			return true;
		}
	}

在Java中,类中的静态方法不能直接调用动态方法。

只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。

3、解决办法

public static class PrimNumber
	{
		public boolean isPrim(int a)
		{
			for(int i=1;i<a/2;i++)
				if(a%i == 0)
					return false;
			return true;
		}
	}

在类名前加上“public static”