这个是改后的类
class Operate {
private static int jishu1 = 0;
private static int jishu2 = 0;
private String a;
public Operate(String a) {
this.a = a;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == 'n') {
jishu1++;
}
if (a.charAt(i) == 'o') {
jishu2++;
}
}
}
public int getJiShu1() {
return jishu1;
}
public int getJiShu2() {
return jishu2;
}
}
你的错误在于private char b[]=a.toCharArray();这句。在数组b里面存放的知识a的地址而已。
相当于对于数组b根本还没有定义。所以报错
这样就可以了:
class Operate {
private static int jishu1 = 0;
private static int jishu2 = 0;
private String a;
private char b[];
public Operate(String a) {
this.a = a;
this.b=a.toCharArray();
}
public void jiSuan() {
for (int i = 0; i < b.length; i++) {
if (b[i] == 'n') {
jishu1++;
}
if (b[i] == 'o') {
jishu2++;
}
}
}
public int getJiShu1() {
return jishu1;
}
public int getJiShu2() {
return jishu2;
}
}
public class Xiti2 {
public static void main(String args[]) {
Operate ope = new Operate("want you to know one thing");
ope.jiSuan();
System.out.println("n的个数是 " + ope.getJiShu1());
System.out.println("o的个数是 " + ope.getJiShu2());
}
}
注意作用域范围
怎么个运行不了?有个异常栈拿来看看?