I am currently attempting to finish my first coding Homework assignment, and My teacher and TA are utterly useless. I have been stuck on this problem and many more for days now with no response other than "There is an error" whenever I ask for help. When I try to run my code in Eclipse, it works perfectly and I have no errors that I have noticed. But, when I try to execute it from the cmd prompt I get the following message:
Exception in thread "main" java.lang.IllegalAccessException: Class org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader can not access a member of class ATM with modifiers "public static"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I have tried googling it, and as far as I have found, the Illegal Access Exception is thrown only for Private and Final methods, which I do not have any of in my code. Any help would be greatly appreciated! Also, please realize that my code may not be good as I have had to teach myself how to code completely.
import java.util.Scanner;
public class ATM {
static Scanner read = new Scanner(System.in); //created a scanner
static String inpCard;
static int listId = -1; //created an int to store the id of the place in which the ATMCard is stored under
static int withdrawlAMT = 0;
public static void main(String[] args) {
cardServices.initializeCardDB(); //enters the array's content
// asks for card number
if(cardServices.insertCard() == true) {
//checks for the pin to be correct
if(pin.processPin() == true) {
int x = account.select();
//if the account selected is checkings, it = 1.
if(x == 1) {
//asks user for how much to withdrawal.
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalCheck(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "checking");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].checkBal);
System.out.println("");
cardServices.returnCard();
}
}
//if the account selected is savings, it = 2.
if(x == 2) {
// asks user for how much to withdrawal
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalSaving(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "savings");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].savingsBal);
System.out.println("");
cardServices.returnCard();
}
}
}
}
}
}
class ATMBal
{
static int one = 50;
static int five = 40;
static int ten = 25;
static int twenty = 20;
static int total = 1000;
}
class ATMCard //Creating the blueprint for all cards
{
public String cardNum = " "; //Made both cardNum and cardPin to string, to avoid octal numbers
public String cardPin = " ";
public float checkBal = 0;
public float savingsBal = 0;
}
class cardServices
{
static ATMCard[] cardList = new ATMCard[5];
public static void initializeCardDB()
{
cardList[0] = new ATMCard();
cardList[0].cardNum = "123456789"; //added card 1's information
cardList[0].cardPin = "1111";
cardList[0].checkBal = 550;
cardList[0].savingsBal = 1275;
cardList[1] = new ATMCard();
cardList[1].cardNum = "135792468"; //added card 2's information
cardList[1].cardPin = "2097";
cardList[1].checkBal = 90;
cardList[1].savingsBal = -1;
cardList[2] = new ATMCard();
cardList[2].cardNum = "019283746"; //added card 3's information
cardList[2].cardPin = "6194";
cardList[2].checkBal = 7915;
cardList[2].savingsBal = -1;
cardList[3] = new ATMCard();
cardList[3].cardNum = "675849302"; //added card 4's information
cardList[3].cardPin = "0071";
cardList[3].checkBal = 790;
cardList[3].savingsBal = 211;
cardList[4] = new ATMCard();
cardList[4].cardNum = "347821904"; //added card 5's information
cardList[4].cardPin = "9871";
cardList[4].checkBal = 113;
cardList[4].savingsBal = 78;
}
public static boolean insertCard()
{
System.out.print("Please insert your card: "); //ask for card number
ATM.inpCard = ATM.read.nextLine(); //read card number
for(int i = 0; i < 5; i++) //start a loop
{
if(ATM.inpCard.compareTo(cardServices.cardList[i].cardNum) == 0) //checks all card numbers in the database, to see if they matched the input card
{
ATM.listId = i;
return true;
}
if(i == 4)
{
System.out.println("I'm sorry, your card was not found in our system.");
insertCard();
return false;
}
}
return false;
}
public static void processCard(int withdrawalAmount, String account) //actual process withdrawing the amount from the card
{
if(account.compareTo("checking") == 0)
cardServices.cardList[ATM.listId].checkBal = cardServices.cardList[ATM.listId].checkBal - withdrawalAmount;
if(account.compareTo("savings") == 0)
cardServices.cardList[ATM.listId].savingsBal = cardServices.cardList[ATM.listId].savingsBal - withdrawalAmount;
}
public static void returnCard() //returns the inpCard through a tempCard to insure all stored data is removed to increase security
{
System.out.println("Thank you for using Bank of America's new ACME ATMs, have a fantastic day!");
String tempCard = ATM.inpCard;
ATM.inpCard = null;
System.out.println("Here is your card: " +tempCard);
}
}
class pin
{
public static boolean processPin()
{
System.out.print("Please enter your pin number "); //asking for pin then read pin
String inpPinNum = ATM.read.nextLine();
for(int i = 0; i < 4; i++) //created loop
{
if(inpPinNum.compareTo(cardServices.cardList[ATM.listId].cardPin) == 0)
{
return true;
}
else
if(i < 3) //checks attempt amount to insure it is less than the allowed 4
{
System.out.println("Incorrect, please re-enter your pin:");
inpPinNum = ATM.read.nextLine();
}
if(i == 3) //if the pin has been incorrectly 4 times, the user is told that the card will be eaten
{
System.out.println("You have entered your pin incorrectly to many times,"
+ " your card is being destroyed. Please go to any Bank of America to recieve a new card");
eatCard(); //the eatCard() command is called to eat the card
}
}
return false;
}
public static void eatCard() //deletes the card in the system, without returning the card
{
ATM.inpCard = null;
}
}
class security
{
public static boolean verifyBalCheck(int withdrawlAmt) //checks checking balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].checkBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].checkBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public static boolean verifyBalSaving(int withdrawlAmt) //checks savings balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].savingsBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].savingsBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public boolean verifyMachineBalance(int withdrawlAmt) //checks ATM Machine Balance
{
if(withdrawlAmt <= ATMBal.total)
{
return true;
}
return false;
}
}
class account
{
public static int select()
{
System.out.print("Would you like to withdrawal from Checkings or Savings? ");
String type = ATM.read.nextLine();
if(type.compareToIgnoreCase("checkings") == 0) //checks to see if the string is checkings, returns 1 if so
{
return 1;
}
if(type.compareToIgnoreCase("savings") == 0) //checks to see if the string is savings, returns 2 if so
{
return 2;
}
return 0;
}
}
class money
{
public static void moneyAmount()
{
System.out.print("How much would you like to withdrawl? ");
ATM.withdrawlAMT = Integer.parseInt(ATM.read.nextLine());
}
}
class dispense
{
public static void dispensing()
{
ATMBal.total = ATMBal.total - ATM.withdrawlAMT; //removes the withdrawalAmt from total
System.out.println("");
System.out.println("Your total withdrawal amount is: " +ATM.withdrawlAMT);
while(ATM.withdrawlAMT >= 20 && ATMBal.twenty > 0) //checks to figure out the biggest bills the machine is able to dispense
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 20;
ATMBal.twenty = ATMBal.twenty - 1;
}
while(ATM.withdrawlAMT >= 10 && ATMBal.ten > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 10;
ATMBal.ten = ATMBal.ten - 1;
}
while(ATM.withdrawlAMT >= 5 && ATMBal.five > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 5;
ATMBal.five = ATMBal.five - 1;
}
while(ATM.withdrawlAMT >= 1 && ATMBal.one > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 1;
ATMBal.one = ATMBal.one - 1;
}
int twenties = 20 - ATMBal.twenty; //Stoes how many of each will be dispensed
int tens = 25 - ATMBal.ten;
int fives = 40 - ATMBal.five;
int ones = 50 - ATMBal.one;
System.out.println("This is comprised of: " +twenties +" twenties, " //prints how much of each bill is being dispensed
+tens +" tens, "
+fives +" fives, and "
+ones +" ones");
}
}
Related
I am relatively new to java programming. I am currently working on building a mini guessing game, as a project to learn more Java. I am having some issues with the following:
Here are the 4 main things I am having trouble solving.
Record the answer for each user, if incorrect.
If the user was correct, skip them in subsequent rounds.
Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players.
Ask if the user(s) wish to play again. If so, reset all values.
Here are the methods that I have written;
import java.io.*;
public class MultiPlayerRandomGame {
// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {
System.out.println("How many users will be playing?");
int players = IO.readInt();
return players;
}
// this method generates and returns a random number
public static int generateRandomNumber() {
int randomNumber = (int) (Math.random() * 100);
return randomNumber;
}
// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {
boolean isGuessCorrect = false;
if (guess == randomNumbers) {
System.out.println("CORRECT!");
isGuessCorrect = true;
} else if (guess > randomNumbers) {
System.out.println("Too High");
} else if (guess < randomNumbers) {
System.out.println("Too Low");
}
System.out.println("test1");
return isGuessCorrect;
}
// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {
for (int n = 0; n < numOfUsers; n++) {
int guessedNumber = numberOfGuesses[n];
/* if (guessedNumber == 0) {
return false;
}*/
if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
return false;
}
}
return true;
}
/* this method is supposed to print out the number of guesses it took each player to guess their correct number
* CORRECTION: change the logic of this method to printing the number of guesses for one player then
* in the main method or wherever, make a for loop that prints out the number of guesses for each player
*/
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {
int n = 0;
for ( int i = 0; i < numOfUsers; i++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
}
}
// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {
boolean userWillPlayAgain;
if (answer.compareToIgnoreCase("no") == 0) {
userWillPlayAgain = false;
}
else {
userWillPlayAgain = true;
}
return userWillPlayAgain;
}
// this method controls the entire game
public static boolean playGame(){
boolean gameTerminate = false;
int numOfUsers = howManyUsers();
int [] randomNumbers = new int[numOfUsers];
int [] numberOfGuesses = new int [numOfUsers];
int [][] numberBoard = new int [numOfUsers][100];
// this for loop assigns the n random number(s) to the n player(s)
for (int n = 0; n < numOfUsers; n++){
randomNumbers[n] = generateRandomNumber();
System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
}
do {
for (int i = 0; i < numOfUsers; i++) {
int guessedNumber = numberOfGuesses[i];
if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
System.out.println("Enter your guess Player " + (i+1) + ":");
int enteredGuess = IO.readInt();
numberBoard[i][guessedNumber] = enteredGuess;
numberOfGuesses[i] = guessedNumber + 1;
if(compareGuess(enteredGuess, randomNumbers[i])){
return true;
}
}
}
/* int n = 0;
* for ( int j = 0; j < numOfUsers; j++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
*/
} while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);
// System.out.println("test");
return gameTerminate;
}
public static void main(String[] args){
boolean playing = true;
while (playing) {
playGame();
System.out.println("Would you like to play again?");
String answer = IO.readString();
playing = playAgain(answer);
}
System.out.println("OK, goodbye!");
}
}
Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number.
Do I need actual Objects to make this happen and track every player or can this still be solved without objects? This is a territory I am unfamiliar with.
Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess.
I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. You can use this new array to skip players who have guessed correctly, also. Once all players are marked true you can return to main.
This won't help improve your current code, but the same game can easily implemented using objects. In my opinion, the code is cleaner and easier to read.
Objects allow you to encapsulate the data required by each class. The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. The values can be accessed by referencing the Person object - e.g. person.numGuesses or person.target.
By using objects, you can keep specific functionality scoped out of the main class. i.e. abstract away the implementation. In a future version of the game, you may want to change the way the target value is incremented; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final List<Person> personList = new ArrayList<>();
private Game(int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
personList.add(new Person(i)); // Fill the player list
}
}
public static void main(String[] args) {
System.out.print("Enter the number of players: ");
Scanner sc = new Scanner(System.in);
int numPlayers = sc.nextInt();
// Initialise with the number of players
Game g = new Game(numPlayers);
g.mainLoop(); // Play the game
boolean playAgain = false;
do {
System.out.print("Do you wish to play again?: ");
String in = sc.next();
playAgain = "yes".equals(in);
if (playAgain) {
g.resetAll();
g.mainLoop();
}
} while (playAgain); // Only loop if they answered "yes"
}
private boolean allCorrect() {
// Check if all players have answered correctly
return personList.stream().allMatch(p -> p.correct);
}
private void resetAll() {
for (Person p : personList) {
p.reset(); // Reset each person
}
}
private void mainLoop() {
while (!allCorrect()) {
for (Person p : personList) {
p.doGuess(); // Ask for the guess
}
}
// Everyone is correct, print the scores.
for (Person p : personList) {
System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
}
}
}
class Person {
final int id;
int numGuesses;
boolean correct;
private int target;
Person(int id) {
this.id = id;
target = new Random().nextInt(100); // Each player has a random target between 0-100
}
void doGuess() {
if (correct) {
// Skip turn if they're already correct
return;
}
numGuesses++;
System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); // Read the guess
if (i == target) {
correct = true;
System.out.println("Correct!");
}
}
void reset() {
target = new Random().nextInt(100); // New target between 0-100
numGuesses = 0; // Reset the counter
correct = false;
}
}
I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.
So in my blackjack program when each game ends the program asks you if you would to play again. My main problem right now is that when the new game is started the score counter just keeps adding the new score to the old score instead of resetting to 0. Im not really sure how to fix it. Here are the two classes where the problem is.
Player class:
public class Player{
private String name;
private Card[] hand; // from 2 - 5 cards allowed
private int cardCount,
chips;
public Player()
{
hand = new Card[5];
chips = 5;
cardCount = 0;
}
public Player(String n){
hand = new Card[5];
name = n;
chips = 5;
cardCount = 0;
}
public void acceptACard(Card c){
hand[cardCount] = new Card();
hand[cardCount] = c;
cardCount++;
}
public void showHand(int startCard)
{
for (int i = startCard; i < cardCount; i++){
System.out.print(hand[i] + "\t"); // displays one card from hand
}
}
public int calcScore(){
int cardScore =0;
int total = 0;
boolean hasAce = false;
for(int i=0; i < cardCount; i++){
cardScore = hand[i].getValue();
if (cardScore >=11 && cardScore <=13)
cardScore = 10;
else if (cardScore == 14){
cardScore = 11;
hasAce = true;
}
total += cardScore;}
if (total > 21 && hasAce == true)
total -= 10;
return total;
}
public void incrementChips(){
chips ++;
}
public void decrementChips(){
chips --;
}
public int getChips(){
return chips;
}
}
BlackJack class:
public class BlackJack {
private Player human,
computer;
private Deck deck = new Deck();
Scanner scan = new Scanner(System.in);
public BlackJack(){
human = new Player("");
computer = new Player ("");
}
public void playGame()
{
int cardTotal = 0;
String answer, answer2;
deck.shuffle();
do{
for ( int i = 0; i < 2; i++)
{
human.acceptACard(deck.dealACard());
computer.acceptACard(deck.dealACard());
}
System.out.print(" Human hand: ");
human.showHand(0);
System.out.print("\n Computer hand: ");
computer.showHand(1);
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if(human.calcScore() == 21 && computer.calcScore() < 21)
System.out.println("You win");
else if (computer.calcScore() == 21 && human.calcScore() < 21)
System.out.println("Computer wins!");
else if (computer.calcScore() == 21 && human.calcScore() == 21)
System.out.println("Tie!");
else if (human.calcScore() < 21)
do{
System.out.println("\nWould you like to hit or stay? Type hit or" +
" stay.");
answer = scan.nextLine();
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
}while(cardTotal < 4 && answer.equals("hit"));
determineWinner();
System.out.println("Would you like to play again? Enter yes or no: ");
answer = scan.nextLine();
}while(answer.equals("yes"));
reportGameStatus();
}
public void dealHand(){
int i = 2; int j =2;
human.acceptACard(deck.dealACard());
System.out.println("New card: ");
human.showHand(i++);
while(computer.calcScore() < 17){
computer.acceptACard(deck.dealACard());
System.out.println();
System.out.println("Computer's new card: ");
computer.showHand(j++);
}
}
public void determineWinner(){
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if (computer.calcScore() > human.calcScore() && computer.calcScore()<22){
System.out.println("Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (human.calcScore() > computer.calcScore() && human.calcScore()
<22){
System.out.println("You win!!");
human.incrementChips();
computer.decrementChips();
}
else if (human.calcScore() == computer.calcScore() )
System.out.println("Tie!");
else if (human.calcScore() > 21){
System.out.println("You bust! The Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (computer.calcScore() > 21){
System.out.println("The Computer busts! You win!");
computer.decrementChips();
human.incrementChips();
}
}
public void reportGameStatus(){
if(computer.getChips() > human.getChips())
System.out.println("Overall winner is the computer!");
else if(human.getChips() > computer.getChips())
System.out.println("You are the overall winner!");
}
}
Any help would be much appreciated.
I think here is your problem:
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
Instead of making new Objects you use the old ones and keep their inner state. That means your construktor is not used a second time and therefore your score, hand, chips are not resetted.
How about trying this:
if(answer.equals("hit"))
{
dealHand();
Player human = new Player();
human.calcScore();
Computer computer = new Coputer();
computer.calcScore();
cardTotal ++;
}
Also you have to make a new Deck everytime you start a new game:
Deck deck = new Deck();
Edit:
If you want to keep your chipCount place it in an Object wich will be initialiset in the constructor of your Blackjack class. After that call a function chipcount.setChipcount(chips); if you want to change the chipCount. Obvisoulsly your chipcount-object should have a getter getChipcounts() as well to get the actual chipCount.
It could look like this:
public BlackJack(){
human = new Player("");
computer = new Player ("");
ChipCount chipCount = new Chipcount(0);
}
here is how your object would be:
class ChipCount{
int chipCount;
public ChipCount(int startChips){
this.chipCount = startchips;
}
public void setChips(int chipsToAdd){
this.chipCount = this.chipcount + chipsToAdd;
}
public int getChips(){
return chipCount;
}
}
Before youre asking. Of course you could make two objects (ChipCountPlayer & ChipCountComputer). Also there is the possibility of giving setChips & getChips another argument like:
class ChipCount{
int chipCountPlayer;
int chipCountComp;
public ChipCount(int startChips){
this.chipCountPlayer = startchips;
this.chipCountComp = startchips;
}
public void setChips(int chipsToAdd, String player){
if(player.equals("player")){
this.chipCountPlayer = this.chipcountPlayer + chipsToAdd;
} else if (player.equals("computer")){
this.chipCountComp = this.chipcountComp + chipsToAdd;
}
}
public int getChips(String player){
if(player.equals("player")){
return chipCountPlayer;
} else if (player.equals("computer")){
return chipCountcomp;
}
}
}
that would be the other solution :P
PS: I am not fond of blackjack, does the computer even have chips? Anyway you could replace the comp with another player if you want to further extent your programm :D
I am supposed to write a program that will prompt the user to enter the hotel rooms that are occupied. Once that is done the user enters -1 and is prompted to enter a random hotel number. If the hotel room is occupied, it prints occupied. If the room is unoccupied, it printer unoccupied. I can't seem to figure out why the unoccupied won't print. Suggestions?
import java.util.Arrays;
import java.util.Scanner;
public class GoughAndreaChapter9
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int [] arr=new int[100];
int counter=0;
int currval=0;
System.out.println("Please enter an occupied hotel room number, -1 to quit ");
do
{
currval = sc.nextInt();
if(currval==-1)
break;
if(currval>0)
arr[counter++]=currval;
}
while(currval !=-1);
// sort using java API
int [] temparr=new int[counter];
for(int i = 0; i<counter; i++)
{
temparr[i] = arr[i];
}
arr = temparr;
Arrays.sort(arr);
//binary search.
int low=0;
int high = counter-1;
System.out.println("Please enter a room to search for: ");
currval = sc.nextInt();
int status=0;
int mid;
while(low<high)
{
if(arr[low]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[high]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
mid = low+high/2;
if(arr[mid]==currval)
{
System.out.println("Occupied");
status=1;
break;
}
else if(arr[mid]<currval)
{
low=mid;
}
else if(arr[mid]<currval)
{
high = mid;
}
}
if(status==0)
System.out.println("Unoccupied");
}
}
Don't ofuscate! Do this:
Room.java
public class Room {
private boolean isOccupied;
public Room() {
this.isOccupied = false;
}
public boolean obtainTheRoom() {
if(!isOccupied) this.isOccupied = true;
return !isOccupied;
}
}
Main.java
import java.util.Scanner;
public final class Main {
private static final int ROOM_AMOUNT = 50;
private static int actualRoom;
private static Scanner cmdin = new Scanner(System.in);
public static void main(String[] args) {
Room[] rooms = new Room[ROOM_AMOUNT];
// Select some random, but static rooms to be occupied
for(int i = 1; i <= ROOM_AMOUNT; i++) {
if(i % 3 - 1 == 0 || i * 2 % i + 10 - 2 == 2) {
rooms[i - 1].obtainTheRoom();
}
}
for(;;) {
System.out.print("Enter a room number:\t");
try {
actualRoom = Integer.parseInt(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
if(rooms[actualRoom - 1].obtainTheRoom()) {
System.out.println("Got the room " + actualRoom + "! Now it's occupied -_-");
} else {
System.out.println("Room Occupied!");
}
}
}
private static void loopRoomNumber() {
System.out.print("That's not a valid room number!\n\n");
try {
actualRoom = Integer.parseInteger(cmdin.next());
} catch(NumberFormatException nfe) {
loopRoomNumber();
}
}
}
That should work. Good luck!
I would change your last else if statements as follows. This will work. Because otherwise you will go in an endless loop;
else if (arr[mid] < currval)
{
low = mid;
--high;
}
else if (arr[mid] > currval)
{
high = mid;
++low;
}
Note that i have decremented the high when the mid value is less than the current value, and incremented the low value when the mid value is greater than the current value
I am writing a program in Java that is a classic BlackJack Game.
The rules are the same,and we make choices as players and the dealer(CPU) plays under some rules.
My code, that is beneath, makes 2 seperate stacks of Deck(s),one for Player and one for Dealer and each one draws from a different Deck but i want to make them both(Player and Dealer) draw from the same Deck(s).
Any suggestions/corrections on my Code ?
import java.util.Random;
import java.util.Scanner;
public class River
{
private int CardNumber;
private int BeginCards;
private int Decks;
private int[] PartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int[] BeginPartialSumArray = {4,8,12,16,20,24,28,32,36,52};
private int PickedCard;
private Random randomGenerator = new Random();
//Constructor without definition
public River()
{
CardNumber = 52;
BeginCards = 52;
}
//Constructor with definition
public River(int Decks)
{
CardNumber = Decks * 52;
BeginCards = CardNumber;
this.Decks = Decks;
//Initialize partial sum array for many decks of cards
for (int i=0; i<10; i++)
{
PartialSumArray[i] = PartialSumArray[i] * Decks;
BeginPartialSumArray[i] = PartialSumArray[i] * Decks;
}
System.out.println();
}
//Create random numbers
private int computeRandomSteps(int CardNumber)
{
//System.out.print("stin random , cardnumber is" + CardNumber);
int randomSteps = randomGenerator.nextInt(CardNumber-1);
return randomSteps;
}
public int nextCard()
{
int steps = computeRandomSteps(CardNumber);
int position=0;
for (int i=0; i<CardNumber; i++)
{
if (steps<= PartialSumArray[i])
{
position = i+1;
break;
}
}
CardNumber--;
return position;
}
public int start()
{
int ShuffleLimit;
PickedCard = nextCard();
System.out.println("Picked card is :" + PickedCard);
int HelpVariable = PickedCard-1;
for (int i=0; i<10; i++)
{
if (i >= HelpVariable)
{
PartialSumArray[HelpVariable] = PartialSumArray[i]-1;
HelpVariable++;
}
}
ShuffleLimit = BeginCards/4;
if (CardNumber<ShuffleLimit)
{
for (int i=0; i<9; i++)
{
BeginPartialSumArray[i] = BeginPartialSumArray[i] * Decks;
}
}
return PickedCard;
}
public int ReturnCardNumber()
{
System.out.println("return cardnumber is " + CardNumber);
return CardNumber;
}
}
class Hand
{
private int points;
private int SumPoints=0;
private boolean Ace = true;
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
public int getPoints()
{
points = myRiver.start();
if (points == 1 && Ace)
{
System.out.println("It is an Ace. Do you want to count 1 or 11?");
points = input.nextInt();
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
public int getPointsDealer()
{
points = myRiver.start();
if (points == 1 && Ace)
{
if (SumPoints + 11 > 21)
{
points = 1;
}
else
{
points = 11;
}
Ace = false;
}
SumPoints += points;
System.out.println("Points are : " + SumPoints);
return SumPoints;
}
}
class Player
{
private int points;
private double account=0;
private double bet;
private boolean WinOrLose;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
public double placeBet()
{
System.out.println("How much do you want to bet?");
bet = input1.nextDouble();
return bet;
}
public double profit(boolean WinOrLose)
{
if (WinOrLose)
{
account += bet;
return account;
}
else
{
account -= bet;
return account;
}
}
public int play(River other)
{
Hand myHand = new Hand();
bet = placeBet();
points = myHand.getPoints();
boolean end = true;
String Choice;
while (end)
{
System.out.println("Make a choice");
Choice = input2.nextLine();
switch(Choice)
{
case "DoubleBet":
bet = bet *2;
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
else
{
System.out.println("Your points are :" + points);
end = false;
break;
}
case "stop":
System.out.println("Your points are :" + points);
end = false;
break;
case "Hit":
points = myHand.getPoints();
if (points > 21)
{
System.out.print("Burned!");
WinOrLose = false;
account = profit(WinOrLose);
end = false;
break;
}
else if (points == 21)
{
System.out.print("You won!");
WinOrLose = true;
account = profit(WinOrLose);
end = false;
break;
}
break;
default:
System.out.println("That is not a choice.");
end = false;
break;
}
}
return points;
}
}
class BlackJack
{
public static void main(String args[])
{
int SumPointsPlayer;
int SumPointsDealer;
boolean WinOrLose = true;
double account;
int Decks;
int BeginCards;
int ThisMomentCards;
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.println("How many decks do you want to begin with?");
Decks = input1.nextInt();
River myRiver = new River(Decks);
Player myPlayer = new Player();
//Calculate the cards we have when the game starts
BeginCards = 52 * Decks;
System.out.println("Do you want to start the game? Yes or No.");
String Repeat;
Repeat = input2.nextLine();
while (Repeat.equals("Yes"))
{
ThisMomentCards = myRiver.ReturnCardNumber();
System.out.println("Cards are : " + ThisMomentCards);
//Player's points for 1 round
SumPointsPlayer = myPlayer.play(myRiver);
//If player catches 21 he wins instantly
if(SumPointsPlayer == 21)
{
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//If player catches >21 he loses instantly
else if(SumPointsPlayer > 21)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Compare the hand of player and dealer and the bigger wins
else
{
//Dealer's points for 1 round
SumPointsDealer = playDealer(myRiver);
//If dealer catches >21 he loses instantly
if(SumPointsDealer>21)
{
System.out.println("Player wins!");
account = myPlayer.profit(WinOrLose);
System.out.println("Your account has :" + account + "dollars!");
}
//Hand of player bigger than the hand of the dealer , player wins
else if (SumPointsPlayer>SumPointsDealer)
{
WinOrLose = true;
account = myPlayer.profit(WinOrLose);
System.out.println("Player wins. Your account has :" + account + "dollars!");
}
//Hand of player smaller than the hand of the dealer , dealer wins
else if (SumPointsPlayer<SumPointsDealer)
{
WinOrLose = false;
account = myPlayer.profit(WinOrLose);
System.out.println("Player lost. Your account has :" + account + "dollars!");
}
//Hand of player is equal with the hand of the dealer , it is tie
else
{
System.out.println("Player and Dealer are tie!!");
}
}
System.out.println("Do you want to continue the game? Yes or No.");
Repeat = input2.nextLine();
}
}
public static int playDealer(River other)
{
boolean bountry = true;
System.out.println("Dealer plays :");
Hand myHand = new Hand();
int SumPointsDealer = myHand.getPointsDealer();
while (bountry)
{
if (SumPointsDealer<17)
{
SumPointsDealer = myHand.getPointsDealer();
}
else if (SumPointsDealer>21)
{
System.out.println("Dealer burned!");
bountry = false;
}
else
{
bountry = false;
}
}
return SumPointsDealer;
}
}
Some Clarifications:
1) The way we draw randomly a card is based on a strange way but this is not the problem its ok the way the program Does draw randomly cards from the Decks
2) Another problem that i noticed is that in class Hand the code that i have in // is not working as it doesnt allow me to have a System.out.println()
Scanner input = new Scanner(System.in);
//Scanner input3 = new Scanner(System.in);
//int Decks = input3.nextInt();
River myRiver = new River();
//River myRiver = new River(Decks);
I wanted to do this so that i will say with how many Decks the user wants to play
You can do better and easier of code is oriented into objects.
i.e. Collections.shuffle(Deck) replaces that whole random conundrum
where Deck is your created Object made of such attributes as LinkedList and a counter[deck value]
hope that helps.
remove object Card from linked list of main deck and move it into the deck of a player. and yes, you can create as many decks as you want that way.
object Card has attributes Value and Suit.