在这里完成初学者......
通过一个无意识概率游戏的在线示例来解决问题。用户杀死龙或被吃掉的地方。我知道游戏使用while循环,所以我尝试使用for循环复制它但失败了。我很好奇为什么for循环不起作用,如果有一些明显的原因需要使用while循环来完成。
下面是工作示例,带有一个while循环来提供上下文。
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
var totalDamage = 0;
while (slaying) {
if (youHit) {
console.log("You hit the dragon and did " + damageThisRound + " damage!");
totalDamage += damageThisRound;
if (totalDamage >= 4) {
console.log("You did it! You slew the dragon!");
slaying = false;
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon burninates you! You're toast.");
slaying = false;
}
}
这是无法正常工作 for循环。
var youHit = Math.floor(Math.random() * 2);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
for(totalDamage=0;totalDamage>3;totalDamage+=damageThisRound){
if(youHit){
console.log("You hit and did "+damageThisRound);
totalDamage += damageThisRound;
if(totalDamage>3){
console.log("You did it! You slew the dragon!");
} else {
youHit = Math.floor(Math.random() * 2);
}
} else {
console.log("The dragon kills you");
}
}
由于
答案 0 :(得分:1)
在public class test extends Activity {
private TextView textView;
private int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
textView = (TextView)findViewById(R.id.text);
set();
}
private void set(){
final String text ="A n d r o i d P r o g r a m m i n g";
final String[] words = text.toString().split(" ");
final Handler handler = new Handler();
handler.post(new Runnable(){
@Override
public void run() {
textView.setText(""+words[i]);
i++;
if(i < words.length) {
handler.postDelayed(this, 1000);
}
}
});
}}
循环中,您将for
设置为totalDamage
,然后拨打0
。而是将totalDamage > 3
循环更改为
for
换句话说,您切换了一个符号,因为您将变量设置为for(totalDamage=0;totalDamage<3;totalDamage+=damageThisRound){
,然后仅在变量大于而不是0
时继续。
答案 1 :(得分:1)
您的循环条件是问题
<xsl:variable name="temp" select="//MappingStatusHistory[Status='A']"/>
<xsl:value-of select="$temp[last()]/Status"/>
<xsl:value-of select="$temp[last()]/Date"/>
&#13;
var youHit, damageThisRound;
for (var totalDamage = 0; totalDamage < 4; totalDamage += damageThisRound) {
youHit = Math.floor(Math.random() * 2);
if (youHit) {
//need to calculare the damage in each loop
damageThisRound = Math.floor(Math.random() * 5 + 1);
snippet.log("You hit and did " + damageThisRound);
} else {
snippet.log("The dragon kills you");
//you need to stop the loop here
break;
}
}
//need this outside of the loop since the increment is in the for loop block
if (youHit) {
snippet.log("You did it! You slew the dragon!");
}
&#13;