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.
Related
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");
}
}
So I'm trying to make this car racing game, modeled after horse races. I've tested the game without the betting component and it works the way I want it to, so thats no problem. But once I started to implement the betting, the program kinda gave up on me. After the user is prompted to enter the bet, the program is just blank.
I'm not getting any error messages and I've tried debugging, but I just really can't figure it out.
I've attached the whole code minus the header; all it is is the names of the cars. (1,2,3)
public static void main(String[]args)throws IOException, InterruptedException{ //start main
Scanner in;
in = new Scanner(System.in);
boolean doAnother = true;
printHeader();
printGame();
while (doAnother) { //start while
int response;
System.out.print("\nWanna play again? 1 = yes, 2 = no.");
response = in.nextInt();
if (response == 1) { // start if loop
doAnother = true;
printHeader();
printGame();
} // end if loop
else {
doAnother = false;
System.out.println("Come back again soon!");
}
} //end while look
} //end main
public static boolean printGame()throws IOException, InterruptedException{
Scanner in = new Scanner(System.in);
Random rd = new Random();
int car = in.nextInt();
if (car >= 4) {
System.out.println("THATS NOT AN OPTION! You automatically lose.");
} else
bet();
System.out.println("Commence race!");
Thread.sleep(250);
int lambo = 0,
nissan = 0,
egg = 0;
int track = 100;
while (true) {
for (int i = 0; i < 50; i++)
System.out.println();
for (int i = 0; i < track; i++) {
System.out.print("-");
}
System.out.println();
lambo = lambo + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
nissan = nissan + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
egg = egg + rd.nextInt(4) + rd.nextInt(2) - rd.nextInt(2);
for (int i = 0; i < lambo; i++) //L
{
System.out.print("."); //distance travelled
}
System.out.println("ℾ");
//
for (int i = 0; i < nissan; i++) //M
{
System.out.print("."); //distance travelled
}
System.out.println("ℿ");
//
for (int i = 0; i < egg; i++) //T
{
System.out.print("."); //distance travelled
}
System.out.println("⅀");
//
for (int i = 0; i < track; i++) {
System.out.print("-");
}
System.out.println();
//
Thread.sleep(250);
//
if (nissan > track || lambo > track || egg > track) {
break;
}
}
if (car == track) {
System.out.println("\nYour car won! Rad!");
return true;
} else {
System.out.println("\nYour car lost... bummer.");
return false;
}
} //printGame
public static void bet()throws IOException, InterruptedException{
Scanner in;
in = new Scanner(System.in);
int money;
int bet;
boolean userWins = true;
money = 100;
while (true) {
System.out.println("You have " + money + " dollars.");
do {
System.out.println("How much do you wanna bet? Or, enter 0 to walk away.)");
System.out.print("$");
bet = in.nextInt();
if (bet < 0 || bet > money) {
System.out.println("Your bet must be between 0 and " + money + '.');
}
} while (bet < 0 || bet > money);{
if (bet == 0) {
System.out.println("Bye.");
break; //walk away
} else {
userWins = printGame();
}
if (userWins == true) {
money = money + bet;
}
if (userWins == false) {
money = money - bet;
System.out.println();
}
if (money == 0) {
System.out.println("Aw shoot, looks like you've are out of money!");
break;
}
}
}
System.out.println();
System.out.println("You walk away with $" + money + '.');
} //end method
You can't have two scanners nested like that. You must use the same scanner from the main method in you other methods or close that scanner
I'm trying to make a simple BlackJack game driven by character input and I'm having a lot of problems in the later part it.
I commented the part that's giving me troubles, the rest doesn't seem to have errors and I did unit test it.
So, what did I do? I created a class that holds the cards drawn and manages them, table, player and dealer are both instances of table.
A table has max 5 cards(for simplicity), every card object comes from the Card class that has a method to add data to the card object.
The main class drives the program and the decisions are made with a character input from the keyboard, I get problems at that point.
import java.io.IOException;
class Table{
Card[] hand = new Card[5];
int counter = 1;
Table() {
for ( int i=0; i<hand.length; i++) {
hand[i]=new Card();
}
hand[0].GetCard();
}
void ReadCards(){
for(int i= 0;i<counter;i++ ) {
System.out.println("The card "+(i+1)+" is " + hand[i].name + " "+ hand[i].seed + "." );
}
}
void DrawCards() {
hand[counter].GetCard();
counter++;
}
boolean isOut() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
if(sum >21) {
return true;
}
}
return false;
}
int TheSum() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
return sum;
}
boolean isWIN(Table p2) {
int sum = 0;
int sump2 = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
for(int i= 0;i<p2.counter;i++ ) {
sump2 += p2.hand[i].value;
}
if (sum>sump2) {
return true;
}
else return false;
}
class Card {
public int value = 0;
public String name = "";
public String seed = "";
void GetCard(){
int positive = 0;
do {
positive = (int) (Math.random()*100) % 10;
}while(positive == 0 );
value = positive;
if(value<10) {
name = String.valueOf(value);
}
else {
positive = 0;
do {
positive = (int) (Math.random()*100) % 3;
}while(positive == 0 );
switch(positive) {
case 1:
name = "J";
break;
case 2:
name = "Q";
break;
case 3:
name ="K";
break;
}
}
positive = 0;
do {
positive = (int) (Math.random()*100) % 4;
}while(positive == 0 );
switch(positive) {
case 1:
seed = "CLUB";
break;
case 2:
seed = "DIAMOND";
break;
case 3:
seed ="SPADE";
break;
case 4:
seed ="HEART";
break;
}
}
}
}
public class BlackJack {
public static void main(String args[])throws IOException {
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char)System.in.read();
}while(flag != 'y' );
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
/*
flag = (char)System.in.read();
while(flag != 'n' ) {
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
flag = (char)System.in.read();
}
System.out.println("The dealer will draw");
while(dealer.TheSum()<18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
*/
System.out.println("WHO WON?");
if (player.isWIN(dealer)){
System.out.println("YOU WIN");
}
else System.out.println("YOU LOSE");
}
}
And yes, I'm not used to java.
Console screenshot of the output here!
Here is an example of fixing your looping issues, however there may be some issue with the game logic, which is out of the scope of this question.
public static void main(String args[]) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char) s.nextLine().charAt(0);
} while (flag != 'y');
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
while (true) {
flag = s.nextLine().charAt(0);
if (flag == 'n') {
break;
}
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
System.out.println("The dealer will draw");
while (dealer.TheSum() < 18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
System.out.println(String.format("The dealer has finished drawing. Dealers score %d. Your score %d", dealer.TheSum(), player.TheSum()));
}
System.out.println("WHO WON?");
if (player.isWIN(dealer)) {
System.out.println("YOU WIN");
} else {
System.out.println("YOU LOSE");
}
}
Output:
Welcome to the BlackJack's table! Press y to start!
y
DEALER
The card 1 is 8 CLUB.
PLAYER
The card 1 is 2 SPADE.
Do you want to draw a card? I'll draw until you'll press n
n
WHO WON?
YOU LOSE
I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
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