Это мой первый вопрос, который я здесь задал. Я сейчас нахожусь в CSCI 2911 в лаборатории, нам нужно запрограммировать базовую игру в кости. Все работало, пока я не добавил простую систему ставок. Как только я это реализовал, это не работает.
Вот код моих классов Java:
Основной класс:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rjohncraps;
import java.util.Scanner;
/**
*
* @author Randall
*/
public class RJohnCraps {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
// Game Object
Game g = new Game ();
// Win Initalization
int wins = 0;
// Money Initlization
int money = 0;
// Bet Amount Initialization
int bet = 0;
// GameInput Initialization
String gameInput = " ";
System.out.println("Want to play a game of Craps? (y/n)");
gameInput = input.nextLine();
// If gameInput is yes or no
switch (gameInput) {
case "Y":
case "y":
case "Yes":
case "yes": //If yes.
// Game do-while
do {
do { // Keep asking until bet is more or equal to zero
System.out.println("How much do you want to bet?");
bet = input.nextInt();
} while (bet <= 0);
// return character in play() [Game.java] to char result
char result = g.play();
switch (result) {
case 'W': // If Wins
System.out.println("You won!");
wins = wins + 1; // Add One Win to Win Count
money = money + bet; // Add Bet Amount to Total Money Amount
break;
case 'L': // If Loses
System.out.println("You lose!");
money = money - bet; // Deduct Bet Amount to Total Money Amount
break;
}
System.out.println("Do you want to play again? (y/n)"); // Ask to play again
gameInput = input.nextLine();
// If gameInput = yes, then it will repeat
} while (gameInput.equals("y") || gameInput.equals("Y"));
// If gameInput = no
System.out.println("Your total wins is "+wins+" wins.");
// It total money is less than zero.
if (money < 0) {
// If it's zero, then it's a negative, so multiply money by -1 to be positive
money = money * -1;
System.out.println("You owe "+money+" dollars.");
} else if (money > 0) { // If total money is more than zero
System.out.println("You earned "+money+" dollars.");
} else { // If total money is zero.
System.out.println("You earned nothing.");
}
break;
// If Don't want to play
case "N":
case "n":
case "No":
case "no":
// Print a nice message
System.out.println("Okay, have a nice day!");
break;
// If Default, Print Invalid Message
default:
System.out.println("Invalid Word");
}
}
}
Класс игры:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rjohncraps;
/**
*
* @author Randall
*/
public class Game {
// Int Variables (set to private)
private int result;
private int point;
// Craps Play
public char play() {
// Dice Object from [Dice class]
Dice d = new Dice();
// Blank Char
char blank = ' ';
// return int from rollTwoDice() to int result
result = d.rollTwoDice();
// Print the results from the Dice Rolls
System.out.print(result+", ");
// If First Roll is 2,3,12
if (result == 2 || result == 3 || result == 12) {
// Return L char
return 'L';
}
// If First Roll 7 and 11
else if (result == 7 || result ==11) {
// Return W char
return 'W';
// If neither 2,3,12,7,11
} else {
// Assigned Result to Point variable
point = result;
// Loop until Result equals 7 or Point (First Roll)
do {
// return integer from rollTwoDice() to result variable
result = d.rollTwoDice();
// print result
System.out.print(result+", ");
} while (result != 7 && result != point);
// if result equals 7
if (result == 7) {
// Return char L
return 'L';
}
// if result equals point (first roll)
if (result == point) {
// return W char
return 'W';
}
}
return blank;
}
}
Класс Dice: (поскольку я не могу разместить более двух ссылок, я опубликую здесь код класса Dice, так как он самый короткий).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rjohncraps;
import java.util.Random;
/**
*
* @author Randall
*/
public class Dice {
// Int Variable for dice one, dice two, and sum of d1 and d2
private int d1;
private int d2;
private int sum;
// Random object
Random bag = new Random();
// Rolling Dice Method
public int rollTwoDice() {
// Sum of Two Dice Initialization
int sum = 0;
// Generate random numbers for dice one and dice two
d1 = bag.nextInt(6)+1;
d2 = bag.nextInt(6)+1;
// Calculate the sum of dice 1 and dice 2
sum = d1 + d2;
// Return sum
return sum;
}
}
Вот что происходит (проблема):
Когда я запускаю код (из основного класса), сначала он спрашивает, хочу ли я играть в Craps, в котором я набираю «y» с клавиатуры.
Затем он спросит, сколько я хочу поставить, и я положил положительное целое число. например, 100.
После этого он напечатает результат бросков кубиков, я получил 8, 9, 8. Если вы знаете игру в кости, это означает, что я выиграл.
Предполагается, что он говорит: «Вы хотите сыграть снова? (Y / n)», в котором я предполагаю ввести либо «y», либо «n», но вместо этого он проигнорирует часть ввода с клавиатуры и просто напечатает общее количество побед, которые я получил, и сумма, которую я заработал.
Вот как выглядит результат:
Want to play a game of Craps? (y/n)
y
How much do you want to bet?
100
8, 9, 8, You won!
Do you want to play again? (y/n)
// I suppose to type something in the keyboard,
// but it skips that and just prints the results.
Your total wins is 1 wins.
You earned 100 dollars.
BUILD SUCCESSFUL (total time: 1 minute 14 seconds)
Я не знаю, что происходит, похоже, что делать, пока это помечено (Комментарий «Game Do-While», похоже, не работает. Что вы, ребята, думаете? Я понятия не имею.
Если вам нужна дополнительная информация, просто дайте мне знать!