忽略了代码行

时间:2016-01-09 20:54:36

标签: java android

我正在尝试清理我的代码以使其在“部分”下运行。 有一个名为intro(),另一个名为second(),依此类推......

切换代码intro())的第一部分转到下一个<时,会出现问题 / strong>一个(second()应首先运行清洁代码,但实际上并不是这样!

code基本上在list上写文字,看起来像聊天,所以intro()是文字的第一部分,然后应该清除聊天并开始编写其他文字在second()内。

这是我的代码,看看:

int counter;
boolean introDone = false;



 //Intro
public void intro(){
        write(answers[counter], buttonText[counter]);
}

public void second(){
            write("So these are the rules:", R.string.go);
}

public void hello(View view){
    Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
    toast.show();
    if(counter <= 2){
    intro();
    }else if(counter == 3){
        clear();
    }else if (counter > 2 && counter < 5) {
    second();}

    counter++;
}

}

这就是诀窍:

    //Intro
public void intro(){
        write(answers[counter], buttonText[counter]);

}

public void second(){
            write("So these are the rules:", R.string.go);
}

public void hello(View view) {
    Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
    toast.show();
    if (counter <= 2) {
        intro();
    } else if(counter == 3) {
        introDone = true;
    }
    if (introDone) {
        clear();
        introDone = false;
    }
    if (counter > 2 && counter < 5) {
            second();
        }

    counter++;
}

}

2 个答案:

答案 0 :(得分:0)

我将假设布尔introDone变量永远不会为真。在intro()方法中,使用if语句对其进行包装,以检查计数器是否为2或更小。没有完整的来源很难说,但我想如果你把代码更改为:

//Intro
public void intro(){

    //if (counter <= 2) {
      //  write(answers[counter], buttonText[counter]);
    //}else{
        introDone = true;
    //}

}

public void second(){
    if(introDone) {
        listViewMother.setAdapter(null); //THIS SHOULD CLEAN THE LIST, BUT INSTEAD WHEN I RUN THE CODE IT LOOKS LIKE IT JUST IGNORES IT
        if (counter > 2 && counter < 5) {
            write("So these are the rules:", R.string.go);
        }
    }
}

public void hello(View view){
    Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
    toast.show();
    intro();
    second();
    counter++;
}

一切都会正常。

从那里你可以看看有关如何递增计数器变量的逻辑,看看是否是问题。

此示例将运行10次调用intro()和second()。

public void hello(View view){
        Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
        toast.show();
        for (int counter = 0; counter < 10; counter++) {
            intro();
            second();
        }

}

答案 1 :(得分:0)

变量计数器和变量 introDone 是如何初始化的?

我假设变量 counter 在程序开始时的值为0,而变量 introDone 为false。如果是这种情况,则不执行 second 部分的代码。例如:

public void hello(View view){
    // --> here, counter=0 and introDone=false
    Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
    toast.show();
    intro(); // --> counter is still 0, so the variable introDone is still false
    second(); // --> because introDone=false then the code is not executed
    counter++;
}