【问题标题】:an array does not get a value数组没有得到值
【发布时间】:2013-11-17 05:50:29
【问题描述】:

下面的代码有问题

public static void SideBet(int numberDice,int bet,int money) {
        System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );

        System.out.println();
        System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
        SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");

        int s = 0;
        int r = 0;

           if (SideBetChoice.equals("Yes")) {
                System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
                int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");

                int[] SBNArray = new int[SideBetNumber];
                int[] sbArray = new int[SideBetNumber];


                    for (s = 0; s <= (SideBetNumber -1) ; s++) {
                       SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
                       sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
                       money = money - sbArray[s];
                       System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
                       System.out.println();
                    }

           } 
           if (SideBetChoice.equals("No")) {
                return;
           }

sbArray 和 SBNArray 没有得到一个值,它一直在崩溃...... 谁能帮帮我,告诉我出了什么问题,为什么 2 个数组没有得到值,因此它们是 null ?

【问题讨论】:

  • SideBetChoice 从不使用类型声明。它是在程序的早期声明的吗?
  • 什么是Console?如果是java.io.Console,我认为它没有readInt 方法。是Scanner 实例吗?如果是这样,它是nextInt 而不是readInt
  • 公共静态控制台输入=新控制台();控制台没有问题...我会检查 SideBetChoice
  • 公共静态字符串 SideBetChoice = "";在 main 中声明为字符串
  • 崩溃在哪一行?

标签: java arrays nullpointerexception


【解决方案1】:

控制台中没有 readInt() 方法。 另外我不确定您是否正确使用控制台,它应该如下所示:

Console console = System.console();

console.readLine("Type something");

只需使用 readLine() 并将其转换为 int:

    Console console = System.console();

    String input = console.readLine("Type a number");
    try
    {
        int myNumber = Integer.parseInt(input);
    }
    catch(NumberFormatException e)
    {
        System.out.println("This ain't a number!");
    }

另外,请不要在变量名或方法名中使用大写字母,这会让人非常困惑,因为您可能会认为它是类或类型。 所以请更改 SBNArray 和 SideBetNumber、SideBetChoice 等的名称。 只有常量应该只用大写字母书写,类和类型以大写字母开头。

编辑: 抱歉,您似乎使用的是 BreezyGUI.Console,因此有一个 readInt() 方法。

您能提供更多信息吗? 我想知道是否显示 readInt() 的文本。

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多