请有人检查我的代码有什么不对,为什么我不能返回count2?

时间:2015-02-05 05:53:28

标签: java return

public int count_two_char(String s, char c, char d){
    int count = 0;

    for(int i = 0; i < s.length(); i++) {
        if(s.charAt(i) == c){
            count = count + 1;
        }

        int count1 = 0;

        for(int i1 = 0; i1 < s.length(); i1++) {
            if(s.charAt(i1) == d){
                count1 = count1 + 1;
            }
            int count2 = count + count1;
        }
    }
    return count2;

错误是count2 cannot be resolved to a variable,但我已经将count2声明为变量,

4 个答案:

答案 0 :(得分:3)

你必须在for循环之前声明count2,

    public int count_two_char(String s, char c, char d){
         int count = 0;
         for(int i=0; i<s.length(); i++){
             if(s.charAt(i) == c){
                 count = count + 1;
     }

         int count1 = 0;
int count2;  // declare count2
         for(int i1=0; i1<s.length(); i1++){
             if(s.charAt(i1) == d){
                 count1 = count1 + 1;

             }
         count2 = count + count1;
         }
         }
        return count2;

试试这段代码。

答案 1 :(得分:3)

你在for循环中初始化了count2。循环存在后,编译器不会记住count2。将上面的count2声明为循环,如adjecent to count。

答案 2 :(得分:0)

在这里,你去找我的朋友:

public int count_two_char(String s, char c, char d) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == c) {
            count = count + 1;
        }

    }
    int count1 = 0;
    for (int i1 = 0; i1 < s.length(); i1++) {
        if (s.charAt(i1) == d) {
            count1 = count1 + 1;

        }
    }
    return count + count1;
}

更优雅一点:

public int countTwoChars(String s, char c, char d) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == c || s.charAt(i) == d) {
            count += 1;
        }

    }
    return count;
}

原始代码中的主要问题是count2在尝试访问时超出了范围。

答案 3 :(得分:0)

count2循环之外声明for

int count1 = 0;
int count2 = 0;
     for(int i1=0; i1<s.length(); i1++){
         if(s.charAt(i1) == d){
             count1 = count1 + 1;

         }
     count2 = count + count1;
     }
System.out.println("count2 "+count2);