1

无法弄清楚为什么我的代码只会在我需要一个字符串时返回一个 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!!");

    }

}
4

3 回答 3

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.
}

如果您想更深入地了解该语言,我建议您查看enums.

(请注意,==在 10 次中有 9 次使用比较字符串是一个坏主意。但是,在这里,我们不需要费心比较字符串内容,而是可以通过比较参考值来摆脱困境。)

于 2012-07-13T15:04:30.720 回答
1

您正在打印ints 的值。试试这个:你生成一个数字,然后根据这个数字选择你的字符串。

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);
于 2012-07-13T15:15:04.800 回答
1

将字符串声明为整数并不会使它们成为整数值。您需要做的是创建一个包含您正在使用的单词的数组。然后生成一个在数组范围内的随机 int 值。

然后,您将从数组中选择单词,该单词位于您拥有的随机 int 指定的位置。

编辑:对不起,我没有阅读你的整个问题。你能告诉我们打印的是什么吗?

于 2012-07-13T15:04:04.130 回答