Craps Project - отладка для неявных синтаксических ошибок - PullRequest
0 голосов
/ 10 мая 2019

Я создаю симулятор Craps с Java на Eclipse IDE, мне ужасно трудно отлаживать вещи, которые, похоже, не указывают на какие-либо ошибки в синтаксисе только во время процесса компиляции.

Я сталкиваюсь с этой проблемой, когда пытаюсь присвоить значение первой ставке на «столе».

Метод Pass() работает не так, как я ожидал, у меня нет немедленных сообщений об ошибках, однако он не хочет компилировать после этой точки, которая находится только на строке 33 в main method.

char answer = keyboard.nextLine().toUpperCase().charAt(0); Эта строка, кажется, является самым большим препятствием на пути к тому, чтобы все мои методы работали гладко повсюду ... из того, что я понимаю.

У меня есть die класс, но это оказалось не проблема, поэтому я не включил его в этот пост.

РЕДАКТИРОВАТЬ: Это вся программа в ее нынешнем виде.Я настраивал левый и правый с обоих концов, чтобы найти подходящие способы для компиляции этого абсолютного беспорядка.

Любая информация очень ценится.Заранее спасибо.

import java.util.Scanner;


public class Craps {
    //Declaring start value of balances
    static double totalMoney = 0.00;
    static double rollMoney = 0.00;
    public static void main(String[] args) {
    //Creating Die Objects
        Die die1 = new Die();
        Die die2 = new Die();
    //Beginning of loop
    do {
    //Displaying the rules for the game
        displayMenu();
    //Array to hold both Dice and create total for the first roll
    //as well as every roll there after
    //Initialized 'purses' for the first bets 
        int dice[] = new int[2];
        int intTotal = 0;   
        int total = 0;
        int passBet = 2;
        double pass = 0.00;
        double dontPass = 0.00;
    //Rolling Dice for the first time in the Round
        die1.Roll();
        dice[0] = die1.getValue();
        die2.Roll();
        dice[1] = die2.getValue();
        intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
    do {
        while(Pass() == true) {
            try{
                pass = getBet();
            } catch(NumberFormatException nfe) {
                System.out.println("Please answer in this numerical format (0.00)");
            }
        }
        while(dontPass() == true) {
            try{
                dontPass = getBet();
            } catch(NumberFormatException nfe) {
                System.out.println("Please answer in this numerical format (0.00)");
            }
        }
        //Display of each individual rolls
        //Display of total
        //Win-Loss-Continue Play check
        switch(intTotal) {
        case 7:
        case 11:
            rollMoney = (pass*passBet);
            dontPass = 0.00;
            System.out.println(dice[0] + " - " + dice[1]);
            System.out.println("Very Nice! Pay the Man!");
            System.out.println("Sorry Don't Pass line, better luck next time.");
            System.out.println("You have made: " + pass);
            System.out.println("Total Earnings: " + totalMoney);
        case 2:
        case 3:
        case 12:
            rollMoney = (dontPass*passBet);
            pass = 0.00;
            System.out.println(dice[0] + " - " + dice[1]);
            System.out.println("Very Nice! Pay the Man!");
            System.out.println("Sorry Pass line, better luck next time.");
            System.out.println("You have made: " + dontPass);
            System.out.println("Total Earnings: " + totalMoney);
        case 4:
        case 5:
        case 6:
        case 8:
        case 9:
        case 10:
            //"Actual" Game of Craps
        do {
        double placeBet[] = {1.2, 1.5, 2.0};
        int hardBet[] = {7, 9};
        int hornBet[] = {15, 30}; 

        //List<Double> place = new ArrayList<Double>();
        //List<Double> hard = new ArrayList<Double>();
        //List<Double> horn = new ArrayList<Double>();

        double place[] = new double[6];
        double hard[] = new double[4];
        double horn[] = new double[4];

        int pBetMax = 6;
        int haBetMax = 4;
        int hoBetMax = 4;

        int pBets[] = new int[pBetMax];
        int haBets[] = new int[haBetMax];
        int hoBets[] = new int[hoBetMax];

            //Gathering Place Bets w/ Location and Value
        if(Place() == true) {
        pBets = getPlace();
        for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
        switch(pBets[pBetOffset]) {
        case 4:
            place[0] += getBet();
        case 5:
            place[1] += getBet();
        case 6:
            place[2] += getBet();
        case 8:
            place[3] += getBet();
        case 9:
            place[4] += getBet();
        case 10:
            place[5] += getBet();
        case 0:
            break;
        }
    }
}
            //Gathering Hardway Bets w/ Location and Value
        if(Hard() == true) {
        haBets = getHard();
        for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
        switch(haBets[haBetOffset]) {
        case 4:
            hard[0] += getBet();
        case 6:
            hard[1] += getBet();
        case 8:
            hard[2] += getBet();
        case 10:
            hard[3] += getBet();
        case 0:
            break;
        }
    }
}               
            //Gathering Horn Bets w/ Location and Value
        if(Horn() == true) {
        hoBets = getHorn();
        for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
        switch(hoBets[hoBetOffset]) {
        case 2:
            horn[0] += getBet();
        case 3:
            horn[1] += getBet();
        case 11:
            horn[2] += getBet();
        case 12:
            horn[3] += getBet();
        case 0:
            break;
        }
    }
}           
        //Redefining the roll separate from the intRoll
        dice = new int[2];
        die1.Roll();
        dice[0] = die1.getValue();
        die2.Roll();
        dice[1]  = die2.getValue();
        total = (dice[0] + dice[1]);
        if(intTotal != total) {
        switch(total) {
            case 11:
                rollMoney += (horn[2] * hornBet[1]);
            case 2:
                rollMoney += (horn[0] * hornBet[2]);
            case 3:
                rollMoney += (horn[1] * hornBet[1]);
            case 12:
                rollMoney += (horn[3] * hornBet[2]);
            case 4:
                if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
                rollMoney += (place[0] * placeBet[3]);
            case 5:
                rollMoney += (place[1] * placeBet[2]);
            case 6:
                if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
                rollMoney += (place[2] * placeBet[1]);
            case 8:
                if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
                rollMoney += (place[3] * placeBet[1]);
            case 9:
                rollMoney += (place[4] * placeBet[2]);
            case 10:
                if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
                rollMoney += (place[5] * placeBet[3]);
            case 7:
                //Wiping the bets clean off the board
                pass = 0.00;
                place = new double[10];
                hard = new double[10];
                horn = new double[10];
                //Redefining the initial roll for the game
                intTotal = 0;
                total = 0;
                totalMoney += (dontPass * 2);
                crapOut();
            }
        }   
        }while(crapOut() == true);
        }
    }while(keepPlaying() == true);
    }while(displayMenu() == true);
}
    /*
     * This method determines if the player will continue after the round is over
     */
    public static boolean keepPlaying() {
        Scanner keyboard = new Scanner(System.in);
        boolean playAgain = false;
        System.out.println("");
        System.out.println("Do you want to roll some more? (Y/N)");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        playAgain = answer == 'Y';
        keyboard.close();
        return playAgain;
    }

    public static boolean crapOut() {
        Scanner keyboard = new Scanner(System.in);
        boolean playAgain = false;
        System.out.println("Crap Out! All Bets are OFF!");
        System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
        System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
        System.out.println("Care to make another wager?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        playAgain = answer == 'Y';
        keyboard.close();
        return playAgain;
    }
    /*
     * This method will assign values to all the bets available to the player
     */
    public static double getBet() {
        System.out.println("How much would you like to bet?");
        Scanner keyboard = new Scanner(System.in);
        String bet = keyboard.nextLine();
        float num;
        num = Float.parseFloat(bet);
        keyboard.close();
        return num;
    }
    /*
     * This method will ask if the player would like to Accept or Press their bet
     */
    public static boolean pressBet(int bet) {
        Scanner keyboard = new Scanner(System.in);
        boolean press = false;
        System.out.println("Press your bet? (Double your initial wager)");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        press = answer == 'Y';
        bet = bet * 2;
        keyboard.close();
        return press;
    }
    /*
     * Methods to check if play would like to place wager
     * Methods to assign those bets to appropriate places on the table
     */
    public static boolean Pass() {
        Scanner keyboard = new Scanner(System.in);
        boolean pass = false;
        System.out.println("Would you like to make a Pass Line Bet?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        pass = answer == 'y';
        keyboard.close();
        return pass;
    }

    public static boolean dontPass() {
        Scanner keyboard = new Scanner(System.in);
        boolean dontPass = false;
        System.out.println("Would you like to make a Don't Pass Line Bet?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        dontPass = answer == 'Y';
        keyboard.close();
        return dontPass;
    }

    public static boolean Place() {
        Scanner keyboard = new Scanner(System.in);
        boolean place = false;
        System.out.println("Would you like to make a Place Bet?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        place = answer == 'Y';
        keyboard.close();
        return place;
    }

    public static int[] getPlace() {
        int counter = 1;
        int max = 6;
        Scanner keyboard = new Scanner(System.in);
        int[] select = new int[6];

        do {
        System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
        System.out.println("Enter bet and hit return for each selection."); 

        select[counter] = keyboard.nextInt();
        counter++;  
        } while(counter <= max || select[counter] != 0);

        keyboard.close();
        return select;
    }

    public static boolean Horn() {
        Scanner keyboard = new Scanner(System.in);
        boolean horn = false;
        System.out.println("Would you like to make a Pass Line Bet?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        horn = answer == 'Y';
        keyboard.close();
        return horn;
    }

    public static int[] getHorn() {
        int counter = 1;
        int max = 4;
        Scanner keyboard = new Scanner(System.in);
        int[] select = new int[4];

        do {
        System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
        System.out.println("Enter bet and hit return for each selection."); 

        select[counter] = keyboard.nextInt();
        counter++;  
        } while(counter <= max || select[counter] != 0);

        keyboard.close();
        return select;
    }

    public static boolean Hard() {
        Scanner keyboard = new Scanner(System.in);
        boolean hard = false;
        System.out.println("Would you like to make a Hardway Bet?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        hard = answer == 'Y';
        keyboard.close();
        return hard;
    }

    public static int[] getHard() {
        int counter = 1;
        int max = 4;
        Scanner keyboard = new Scanner(System.in);
        int[] select = new int[4];

        do {
        System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");     
        System.out.println("Enter bet and hit return for each selection."); 

        select[counter] = keyboard.nextInt();
        counter++;  
        } while(counter <= max || select[counter] != 0);

        keyboard.close();
        return select;
    }
    /*
     * Method to display rules and parameters of game prior to playing
     */
    public static boolean displayMenu() {
        System.out.println("Welcome to the Crosby Casino!");
        System.out.println("The Game is Craps, Rules Are:");
        System.out.println("If a 7 or 11 is the first roll on the table,");
        System.out.println("Pass bets get paid on the first roll!");
        System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
        System.out.println("Don't pass bets get paid on the first roll!");
        System.out.println("If any other value is rolled, the game begins..");
        System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
        System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
        System.out.println("During the duration of the roll you can make up to 3 separate side bets");
        System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
        System.out.println("'Hard bets' -  (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
        System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
        System.out.println("The table minimum is $5.00 to play");
        System.out.println("All side bet minimums are $1.00 to play");
        Scanner keyboard = new Scanner(System.in);
        boolean menu = false;
        System.out.println("Would you like play?");
        char answer = keyboard.nextLine().toUpperCase().charAt(0);
        menu = answer == 'Y';
        keyboard.close();
        return menu;
    }

}

1 Ответ

0 голосов
/ 10 мая 2019

Java-массивы 0-origin .По сути, это означает, что первый элемент в массивах имеет индекс 0, а не 1, как показывает ваш массив dice.Таким образом, вам необходимо заменить dice[1] и dice[2] на dice[0] и dice[1] соответственно.

РЕДАКТИРОВАТЬ На основе новой информации из комментариев:

Это звучит как новая ошибкачем AIOOBE, который вы ранее описали.Проблема с вашим кодом заключается в том, что вам необходимо убедиться, что вы используете Scanner hasNextLine() метод перед вызовом метода nextLine().По сути, вы звоните nextLine(), когда нет «следующей линии», вызывая NoSuchElementException.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...