Cannot make a static reference to the non-static method numJewelsInStones(String, String) from the type Solution
无法从类型解决方案对非静态方法numjewelsingstones(string,string)进行静态引用
import java.util.Scanner;
class Solution {
public int numJewelsInStones(String J, String S) {
char[] A=J.toCharArray();
char[] B=S.toCharArray();
int n=0;
for(char y : B){
for(char x : A ){
if(x==y){
n++;
}
}
}
return n;
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String J= scan.nextLine();
String S= scan.nextLine();
System.out.println( numJewelsInStones(J,S));//应该对类实例化后再引用
}
}
正确答案
import java.util.Scanner;
class Solution {
public int numJewelsInStones(String J, String S) {
char[] A=J.toCharArray();
char[] B=S.toCharArray();
int n=0;
for(char y : B ){
for(char x : A ){
if(x==y){
n++;
}
}
}
return n;
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String J= scan.nextLine();
String S= scan.nextLine();
Solution T=new Solution();
System.out.println( T.numJewelsInStones(J,S));
}
}
类中静态的方法或者属性,本质上来讲并不是该类的成员,在java虚拟机装在类的时候,这些静态的东西已经有了对象,它只是在这个类中”寄居”,不需要通过类的构造器(构造函数)类实现实例化;而非静态的属性或者方法,在类的装载是并没有存在,需在执行了该类的构造函数后才可依赖该类的实例对象存在。所以在静态方法中调用非静态方法时,编译器会报错(Cannot make a static reference to the non-static method func() from the type A
网友评论