Blackjack.java while loop input validation - java

I am creating a simple Blackjack java program and I am stumped with the while loop input validation. When a user is requested to draw a card, he/she has the option: (y/n) to choose from as well as if they want to play again. My problem is when I am prompted to draw a card and I choose y, that character only should prompt a card draw...but it seems as if any character would do that trick. The same goes for the play loop if I want to play again. Also when I am prompted to play again I want to return to the beginning of the while loop but I can't seem to call on that function. I need help! Here is my code:
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Scanner keyboard = new Scanner(System.in);
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = keyboard.next().charAt(0);
}
if (cardTotal > 21) {
System.out.println("Bust");
System.out.print("Would you like to play again? (y/n): ");
play = keyboard.next().charAt(0);
}
}
}
}
}

There's a few problems with this code.
You will incur an infinite for loop because the drawAgain is never reset to n if the the points value is > 21.
In order to enforce the user must specify either a yes or no, you must check for it. Below does so with a while loop.
The play variable is never reset which forces the user to play until busting, then choose if want to keep playing or not.
The below addresses these issues. This should be what you want.
import java.util.Random;
import java.util.Scanner;
public class BlackJack
{
public static char getValidInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
while(!input.equals("yes") || !input.equals("no")){
System.out.println("please input yes or no");
input = keyboard.next();
}
return input.charAt(0);
}
public static void main(String[] args)
{
char play = 'y';
char drawAgain;
int card1, card2;
int nextCard = 0;
Random number = new Random();
while (play != 'n')
{
card1 = number.nextInt(10) + 1;
card2 = number.nextInt(10) + 1;
System.out.print("First cards: ");
System.out.println(card1 + ", " + card2);
int cardTotal = card1 + card2;
System.out.println("Total: " + cardTotal);
System.out.print("Draw again? (y/n): ");
drawAgain = getValidInput();
while (drawAgain != 'n')
{
int card3 = number.nextInt(10) + 1;
System.out.println("Card: " + card3);
cardTotal += card3;
System.out.println("Total: " + cardTotal);
if (cardTotal <= 21) {
System.out.print("Draw Again? (y/n): ");
drawAgain = getValidInput();
}else{ //if (cardTotal > 21) {
System.out.println("Bust");
drawAgain ='n';
}
}
play = getValidInput();
}
}
}

Related

How to combine two programs in one class

I have created two games and now I am working on menu
It should run each game after user selected each of them
Menu Must look like this:
Hello! Type 'letter' or 'number' to choose game
Heres first game:
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
System.out.println("Guess a number between 1 and 100:");
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
int guess = 0;
while (guess != theNumber)
{
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Heres the second
import java.util.Scanner;
public class GuessTheLetter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}}
Must i use multiple classes, or put everything into 1, how can i combine theese two games in one?
You can put each game into one function and then just call them in the main of that class. You do not need 2 classes for this. You can also add a condition that would decide which function to call.

Having trouble w/ returning and passing values; "counting"

Our task was to create a guessing game, where the computer would generate a number and the user was prompted to guess. We were to create a method to play only one game, and then create a while loop in the main to make the game playable again. In the end, we need to show statistics. I'm having trouble with showing the "best game." That is a game where the amount of guesses is the least.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static final int MAX = 100;
// This is the main. Here we can see a do/while loop
// and a few variables that were created to compliment it.
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
do {
totalGuess = game(console);
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
statistics(totalGames, totalGuess);
}
// This method prints out the intro.
public static void intro() {
System.out.println("This program allows you to play a guessing
game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAX + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.\n ");
}
// This method plays the game only once. It's later used in the main.
// Returns the
// number of guesses for one game.
public static int game(Scanner console) {
Random rand = new Random();
int random = rand.nextInt(MAX) + 1;
System.out.println("I'm thinking of a number between 1 and " + MAX + "
... (it's " + random + " )");
System.out.print("Your guess? > ");
int guess = console.nextInt();
int count = 0;
do {
if ((random - guess) > 0) {
System.out.println("It's higher.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if ((random - guess) < 0) {
System.out.println("It's lower.");
System.out.print("Your guess? > ");
guess = console.nextInt();
count++;
}
else if (random == guess) {
count++;
}
} while (random != guess);
if (count == 1) {
System.out.println("You got it right on the first guess!!");
}
else {
System.out.println("You got it right in " + count + " guesses.");
}
return count;
}
// This method prints out the statistics.
public static void statistics(int x, int y) {
System.out.println("total games = " + x);
System.out.println("total guesses = " + (y));
System.out.println("guesses/game = ");
System.out.println("best game = ");
}
}
Have a look when totalGuess is assigned:
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
intro();
String s = "";
int totalGames = 0;
int totalGuess = 0;
// ^ Initialized to zero
do {
totalGuess = game(console);
// ^ Assigned (not added) to the return value from game.
// Did you mean: totalGuess += game(console); ?
System.out.print("Do you want to play again? ");
s = console.next();
totalGames++;
} while (s.equals("y") || s.equals("Y") || s.equals("Yes") ||
s.equals("yes") || s.equals("Yes"));
totalGuess = totalGuess;
// ^ Assigned to itself. No action.
statistics(totalGames, totalGuess);
}

Having issues with having a program re-run

I am writing a program that will ask the user to guess a random number 6 times. The program has to ask if they want to play again and will keep a running total of the wins/losses.
How would I have the program rerun?
heres the code:
import java.util.Scanner;
import java.util.Random;
public class Project {
public static void main(String[] args) {
String input;
double guess = 0;
int number;
double wins = 0;
double losses = 0;
String repeat;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to Higher/Lower!");
System.out.println("Enter your name: ");
input = keyboard.nextLine();
while(input.equalsIgnoreCase("yes")); {
number = randomNumbers.nextInt(100) + 1;
System.out.println("I've chosen my number, " + input + "You only have 6 tries, good luck!"); }
for(int num = 1; number != guess && number <= 6; num++) {
System.out.println("Enter guess " + num + ":");
guess = keyboard.nextDouble();
if(guess < number)
System.out.println("higher.");
else if(guess > number)
System.out.println("lower.");
else
System.out.println("Congratulations!"); }
if(guess == number) {
System.out.println("You guesses my number!"); wins++; }
if(guess != number) {
System.out.println("Sorry, " + input + " my number was " + number +
"You lose!"); losses++; }
System.out.println("Do you want to play again? (Yes/No): ");
repeat = keyboard.nextLine();
if(input.equalsIgnoreCase("no")); {
System.out.println("Thanks for playing!"); }
System.out.println(wins + " wins");
System.out.println(losses + " losses");
}
}
It is skipping over asking me if i want to play again or not and i dont know what kind of loop to use
Wihtout your code, I'm assuming this is what you need.
boolean doContinue = true;
do {
//guess random number 6 times
//do you want to continue?
// yes -> doContinue = true;
// no -> doContinue = false;
} while (doContinue );
I would suggest making your loop a do-while loop like this:
do {
for (int i=0; i<6; i++){
/*
insert code for the guessing/checking/etc.
*/
}
System.out.print("Would you like to continue? [Y/n] ");
} while (scan.next().toUpperCase().charAt(0) != 'Y');

How can i add the random number to my total for java(blackjack)?

This is my code:
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
System.out.println("Card: "+ (random.nextInt(10)));
total = total + (random.nextInt(10));
System.out.println("Total: "+ total);
}
}
}
When I enter n, how can I make it so the program exit, instead of printing out the total again?
Check this out:
public class Assignment2 {
public static void main(String args[]){
int next = 0;
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;
System.out.println("Total: "+ total);
}
if (exit.equals('n'))
system.exit(0);
}
}
Now the program exists after you enter n by calling system.exit(0).
You need to call nextInt just once, so you won't create 2 different random numbers. So I put the first call into a variable next so you could use it as many times as you please without having to call nextInt again.
If you want the program to exit immediately after the user enters n, you will want to put the if statement right after the exit = stdin.next().charAt(0);
If you want to exit the loop, you can break from it. Basically you have to do this(I have written comments to highlight the alterations)-
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
//you need to check here if the user entered 'n'. I have used a break opertion
//to break from the loop and print the total outside the loop. But if you want
//to exit the program altogether, just replace break with exit(0) :)
if(total >= 21 or exit == 'y') {
break;
}
//As Idos correctly pointed out that by calling random.nextInt(10) two
//times you have a very big chance of creating two different random numbers.
//So it makes sense to put the first call into a variable nextNumber.
int nextNumber = random.nextInt(10);
total = total + (nextNumber);
//Now we should again check for total. If it is greater than or equal to 21
//I am again breaking from the loop. Feel free to replace break with exit(0).
if(total >= 21) {
break;
}
System.out.println("Total: "+ total);
}
System.out.println("Your total- "+ total);
}
}

Rock paper scissors, play again?

For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;

Categories

Resources