无法弄清楚为什么我的代码只在需要字符串时才返回Int,并且帮助会很棒。代码如下。我尝试将变量声明为String而没有运气。
我想要返回3个随机字符串:cherry,grape,bell或x
import java.util.Scanner;
import java.util.Random;
public class slot {
public static void main(String[] args)
{
String answer = "y";
int cherry;
int grape;
int bell;
int x;
Random generator = new Random(); // random generator
Scanner scan = new Scanner (System.in); // scanner class
System.out.println("Would you like to play the slot machine?(y/n): ");
answer = scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
cherry = generator.nextInt(5); // generates a random number
grape = generator.nextInt(5);
bell = generator.nextInt(5);
System.out.println("The three numbers of the slot machine are: " + cherry +grape +bell);
if(cherry == grape && grape == bell)
{
System.out.println("JACKPOT! All three of the same");
}
if(cherry == grape || cherry == bell || grape == bell )
{
System.out.println("Close, you got two of the same!!");
}
else
{
System.out.println("Not a winner");
}
System.out.print("Try again?(y/n): ");
answer = scan.nextLine();
System.out.println();
}
System.out.println("Bye!!");
}
}
答案 0 :(得分:8)
我会这样表达:
// The different results each "wheel" / "column" on the slot machine.
String[] results = { "cherry", "bell", "grape", "x" };
// Create a random result for each wheel.
String wheel1 = results[generator.nextInt(results.length)];
String wheel2 = results[generator.nextInt(results.length)];
String wheel3 = results[generator.nextInt(results.length)];
然后继续您的if
语句。 (但是对于第二和第三个陈述,请else if
。)
if (wheel1 == wheel2 && wheel2 == wheel3) {
// jackpot
} else if (wheel1 == wheel2 || wheel2 == wheel3 || wheel1 == wheel3) {
// two equal
} else {
// all three different.
}
如果您想深入了解该语言,我建议您查看enum
s。
(请注意,使用==
比较字符串在9个案例中有10个是坏主意。但是,我们不需要费心去比较字符串内容但可以逃脱通过比较参考值。)
答案 1 :(得分:1)
将字符串声明为int并不会使它们成为整数值。你需要做的是创建一个包含你正在使用的单词的数组。然后生成一个随机int值,该值在数组范围内。
然后你将从数组中选择你所拥有的随机int所指定位置的单词。
编辑:对不起,我没有看完你的整个问题。你能告诉我们印刷什么吗?答案 2 :(得分:1)
您正在打印int
的值。试试这个:你生成一个数字,根据这个数字你选择你的字符串。
Random generator = new Random();
int a = generator.nextInt(5);
int b = generator.nextInt(5);
int c = generator.nextInt(5);
String roll1 = null;
switch(b){
case 1: roll1 = "cherry";
break;
case 2: roll1 = "grape";
break;
case 3: roll1 = "bell";
break;
default: roll1 = "xxx";
break;
}
//repeat for b and c with roll2 and roll3
System.out.println(roll1);