所以我试图创建一个摇滚/纸张/剪刀应用程序,但我遇到了问题。在下面的代码中"随机r"选择1-3号并将其分配给R / P / S.该部分有效,但我的switch语句中的评分或Toast代码没有。 " case"旁边的整数应该是选择正确的价值吗?如果有人能找到我的问题,我将不胜感激。
public void decide(){
int playerTotal = 0;
int computerTotal = 0;
TextView pTotal = (TextView)findViewById(R.id.playerTotal);
TextView cTotal = (TextView)findViewById(R.id.compTotal);
pTotal.setText(Integer.toString(playerTotal));
cTotal.setText(Integer.toString(computerTotal));
int cpu = r.nextInt(3); //Randomizer will choose 1-3
if(cpu == 1) {
cpuChoice = "rock";
imgCpu.setImageResource(R.drawable.rock);
}
else if(cpu == 2){
cpuChoice = "paper";
imgCpu.setImageResource(R.drawable.paper);
}
else if(cpu == 3){
cpuChoice = "scissors";
imgCpu.setImageResource(R.drawable.scissors);
}
String winOrLose = "";
switch (cpu){
case 1:
if(myChoice == "rock") {
winOrLose = "Stalemate!";
}
if(myChoice == "paper") {
winOrLose ="paper beats rock! You won this round!";
playerTotal++;
}
if(myChoice == "scissors") {
winOrLose = "rock beats paper! You lost this round!";
computerTotal++;
}
Toast.makeText(MainActivity.this,winOrLose, Toast.LENGTH_SHORT);
break;
case 2:
if(myChoice == "rock") {
winOrLose = "paper beats rock! You lost this round!";
computerTotal++;
}
if(myChoice == "paper") {
winOrLose = "Stalemate!";
}
if(myChoice == "scissors") {
winOrLose = "scissors beats paper! You won this round!";
playerTotal++;
}
Toast.makeText(MainActivity.this,winOrLose, Toast.LENGTH_SHORT);
break;
case 3:
if(myChoice == "rock") {
winOrLose = "rock beats scissors! You won this round!";
playerTotal++;
}
if(myChoice == "paper") {
winOrLose = "scissors beats paper! You lost this round!";
computerTotal++;
}
if(myChoice == "scissors") {
winOrLose = "Stalemate!";
}
Toast.makeText(MainActivity.this,winOrLose, Toast.LENGTH_SHORT);
break;
}
}
答案 0 :(得分:0)
正如@Seelenvirtuose所说,nextInt()将生成0-2但不是1-3 之间的值(假设你发送3作为nextInt()方法的参数)。
因此要准确生成1-3之间的值,您可以尝试下面的代码。
int minimum = 1;
int maximum = 4;
Random random = new Random();
int randomValue = random.nextInt( maximum - minimum ) + minimum;
要了解有关在指定范围之间生成随机数的详情,请访问here
答案 1 :(得分:0)
我明白了!得分不起作用,因为每次调用该方法时,得分将重置为0,因此我将其交换到方法的末尾并擦除零。对于吐司,我必须在最后添加.show(),如下所示:
Toast.makeText(MainActivity.this,winOrLose, Toast.LENGTH_SHORT).show();
感谢大家的建议!随机为我工作1-3,但我把它改为0-2在技术上是正确的。