I am making a program called "count 21". How it's supposed to work is, "Two people play the game of Count 21 by taking turns entering a 1, 2, or 3, which is
added to a running total. The player who adds the value that makes the total exceed
21 loses the game. Create a game of Count 21 in which a player competes against the
computer, and program a strategy that always allows the computer to win. On any
turn, if the player enters a value other than 1, 2, or 3, force the player to reenter the
value."
I am having trouble figuring out how I should do this, this is what I have so far:
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Count21 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x; //running total
int y; //input num
String strInput = "";
String message = "";
String answer = "";
do {
strInput = JOptionPane.showInputDialog(null, "Welcome to Count 21. \n In this game you will play against "
+ "the computer and add the numbers 1, 2, or 3 together. \n Whoever pushes the "
+ "numbers over 21 loses. \n Do you want to add 1, 2, or 3? "
+ "(please enter the number you choose.");
y = Integer.parseInt(strInput);
x++;
if (y == 1) {JOptionPane.showMessageDialog(null, "You chose the number 1."
+ " 1 will be added to the running total of" + (x + 1) +" .");
}
else if (y == 2) {JOptionPane.showMessageDialog (null, "You chose the number 2."
+ "2 will be added to the running total of" + (x + 2) + " .");
}
else if (y == 3) {JOptionPane.showMessageDialog (null, "You chose the number 3."
+ "3 will be added to the running total of" + (x + 3) + " .");
}
else{
JOptionPane.showMessageDialog(null, "You didn't type a valid number, please try again. \n");
}
} while (x > 21);
}
}
After the program runs and the user types in the number they chose the program ends. This is all I have so far, but I am stuck on how to keep the number's from the user adding until it reaches 21. I also am unsure of how to make the computer win the game. I think I should be using a for loop?
Any advice or comments are greatly appreciated. I apologize if my code or question is unclear.
As suggested in the comments, you shouldn't be incrementing xby one for each time a value is entered. This also causes further problems as when invalid numbers are entered it would still get incremented. Instead you should be checking the value of y and then adding the appropriate amount within the conditional logic (IF statement). This should also simplify the output messages contained within the logic, as you shouldn't need to add anything to x when printing it.
Again, as stated in the comments, the while condition should be x < 21.
Related
I'm really, really stuck and confused. I've net searched several times, and can't find anything that helps me with this precise homework problem.
Involved: Java, while loops, randomly generating numbers, and scanner console input.
We have to finish the code in main method so it takes two separate inputs from the console and generates a number of "rolls" , then displays the results when they are a pair of numbers, one even, one odd.
Edit: It was pointed out to me my phrasing was confusing. Joseph Larson phrased it better:
"You are to ask for the upper bound of the random numbers, and then a number of times to run, correct?" Yes, that's it.
I have two primary problems. If these get fixed, I'm fairly sure I can figure out the rest.
1) I know I'm supposed to do something to complete the while loop, but nothing I've tried gets the required results.
2) I think I've declared the randUpBound and oddeven items incorrectly, but I can't figure out what I might have done wrong if I have.
The weirdest part is most of my attempts have created a blank infinite loop -nothing is displayed, but IntelliJ swears the program is running, and it doesn't stop until I make it stop. Not even the strings in quotes appear.
Expected display and code below. I've stuck //added to the lines where it's my code, and left in the teacher's instructions.
Thanks for any help you can give!
Expected Display
Enter random upper bound? 12
Enter number of odd even pairs to count? 2
Numbers rolled: 11, 2
Odd+even pair found! 11,2
Numbers rolled: 1, 8
Odd+even pair found! 1, 8
Numbers rolled: 1, 1
Total Roll count: 6
Code
import java.util.*; //added
public class OddEvenPairs {
public static void main(String[] args) {
//.....[add in missing code here - make declarations and add console input for the random number upper bound,
// and the number of odd-even pairs to be counted]
//read two consecutive numbers - fencepost
Scanner console = new Scanner(System.in); //added
Random rand = new Random(); //added
int randUpBound = console.nextInt(); //added
int oddeven = console.nextInt(); // added
System.out.println("Enter random upper bound? " + randUpBound); //added
System.out.println("Enter number of odd even pairs to count? " + oddeven); //added
int roll1 = rand.nextInt(randUpBound);
int roll2 = rand.nextInt(randUpBound);
System.out.println("Numbers " + roll1 + ", " + roll2);
int rollcount = 2;
int oddEvenNum = roll1 + roll2;
//process the numbers
while (oddeven < oddEvenNum) {
oddeven = oddEvenPair(roll1, roll2, oddeven);
roll1 = rand.nextInt(randUpBound);
roll2 = rand.nextInt(randUpBound);
System.out.println("Numbers " + roll1 + ", " + roll2);
rollcount += 2;
//.....[complete missing code here]
}
}
//method to figure out odd-even pair
public static int oddEvenPair(int roll1, int roll2, int oddeven) {
//boolean oddEvenFound = false;
if (roll1 % 2 == 1) {
if (roll2 % 2 == 0) {
//oddEvenFound = true;
oddeven++;
System.out.println("Odd even " + oddeven);
System.out.println("Odd+even pair found!" + roll1 + "," + roll2);
}
}
return oddeven;
}
}
Okay, there are a few problems with your code. First, this:
int randUpBound = console.nextInt(); //added
int oddeven = console.nextInt(); // added
System.out.println("Enter random upper bound? " + randUpBound); //added
System.out.println("Enter number of odd even pairs to count? " + oddeven); //added
These will happen in order, which means you'll accept input from the console and THEN prompt the user. This will be confusing.
Next, I would change the variable name for oddeven to something like "numberOfTries". Oddeven doesn't really explain what it's really for.
Once you have those two numbers, you need a loop.
for (int thisTry = 1; thisTry <= numberOfTries; ++thisTry) {
...
}
This will then run your code the proper number of times.
Inside that loop is where you will generate your two random numbers and then call your oddEvenPair method. Then just print out the results.
Your function is really weird and probably doesn't do what you want.
Here's the thing. You let yourself get confused by thinking about too much at once. Break it down. How would you do it on paper? Break it into little pieces. You really have 5:
-Get data from the user (with prompts)
-Loop the proper number of times
-Generate two random numbers in the proper range
-Determine both odd/both even/one of each
-Print the results
Think about things in those terms, and then the amount of code for each step is REALLY small.
I am writing a program in which the random method generates a random number between 1 and 100, and then the user guesses what the number is.
Everything in the code I built works fine so far, except the part where the program also calculates the number of user guess attempts.
I know the general idea of how to get the user attempt count: create a count-tracking variable and then increment it with each user entry. Now matter how or where I apply the count-tracking variables, the number of user attempts is always 2, even though there are far more actual attempts. I Googled this issue, and tried different ideas from results (ex: put count++ into every "if/else" statement), but nothing works.
Can anyone tell what is wrong with my code, and why it is always showing 2 as number of user attempts? Thank you in advance for any help.
System.out.println("Enter a number between 0 and 100: ");
int randomDigit = (0 + (int) (Math.random() * 101));
while (true) {
Scanner scr = new Scanner(System.in);
int guess = scr.nextInt();
int guessCount = 0;
guessCount++;
guessCount = guessCount + 1;
if ((guess < 0) || (guess > 100)) {
System.out.println("You entered an invalid number. \nPlease enter a valid number.");
} else if (guess > randomDigit) {
System.out.println("Your guess is too high. \nPlease enter another guess.");
} else if (guess < randomDigit) {
System.out.println("Your guess is too low. \nPlease enter another guess.");
} else if (guess == randomDigit) {
System.out.println("Congradulations, you found the number! It is " + randomDigit
+ ".\nThe number of attempts it took you to guess the correct answer is: " + guessCount + ".");
break;
}
}
The above code always has 2 as number of user attempts.
Move this line:
int guessCount = 0;
Outside the loop, as you are constantly repeating the initialization of the variable, and thus, not actually counting it.
When you use a counter, always define it outside your while/for loops.
Good luck
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am new to coding. Please be gentle with me.
I have been charged with creating a program that compares the scores of two competing volleyball. To win a match in volleyball, a team must get 25 points. But the team must also win by 2. These two teams are going to play five matches.
The program should accept from the user the scores for each team one match at a time. If at any time that user enters scores that violate the 25-point rule or the “win by 2” point rule, print an error on the screen and make the user enter both scores again.
When the user is finished entering the scores, print which team won the game, that is the team that won the most matches.
You have to use arrays and loops in this assignment.
My program is only scoring the first set of scores in the array.
How do I make it store all five sets of scores?
public static void main(String[] args) {
int team1[];
int team2[];
team1=new int[5];
team2=new int[5];
int counter1=0;
int counter2=0;
int k = 0;
for (int i=0;i<=4;i++){
Scanner scanint = new Scanner(System.in);
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
////////////////////////////////////////////
if (team1[i] < 25 & team2[i] < 25){
System.out.println("That cannot be. One team must get at least 25 points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else if (team1[i] - team2[i] < 2 || team2[i] - team1[i] < 2){
System.out.println("That can't be. One team must win by at least two points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else {
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
/////////////////////////////////////////////
if (team2[i] < team1[i]){
counter1++;}
else{ counter2++;}
}
if (counter1 > counter2) {
System.out.println("Team 1 has won the game.");}
else{
System.out.println("Team 2 has won the game.");
}
Well, there are only a few rules for finished games that I see:
Neither team can have negative points.
At least one team has to have 25 or more points.
The points for a team can't be above 25 unless it's exactly two points above or below the other team.
So, how do we do this? With some if statements for each rule. For the first rule:
if ((team1 < 0) || (team2 < 0)) {
System.err.println("A score cannot be negative!");
i--;
continue;
}
For the second rule:
if ((team1 < 25) && (team2 < 25)) {
System.err.println("At least one team has to have 25 or more points!");
i--;
continue;
}
For the third rule (this can be converted into one if statement with an &&, but I've made it a bit simpler to understand):
if ((team1 > 25) || (team2 > 25)) {
if ((team1 - team2 != 2) && (team2 - team1 != 2)) {
System.err.println("If a team has more than 25 points, the other team must be two points away from it!");
i--;
continue;
}
}
Note that the continue; means to go to the next iteration of the loop you're in. So, you go to the previous iteration with i--; and you go to the next iteration with continue;. This is a trick to allow you to restart the current iteration of the loop you're in.
Also, I wouldn't use arrays unless I used the scores somewhere outside the initial data input loop (though you should follow the rules for the assignment and use them anyway). I'd immediately point out when a game's scores were invalid and I'd keep track of the wins for both teams in some variables, like int team1Wins = 0; and int team2Wins = 0;.
I'm new to this so sorry if I am a bit confusing
So this is my code, its a game based around 2 players adding 1 or 2 to the variable "counter" the one who puts the final 1 or 2 adding all the numbers up to 21 wins.
So what I would like to have help with is that I want to lock the user input to only be able to select 1 or 2, not anything else because that would break the rules of the game. Also I would like to have a way to determine who won, player 1 or player 2. Like counting the amount of times the loop happens, so I can distinguish if player 1 or 2 one.
Any help would be appreciated! Thanks!
package hemtenta;
import java.util.Scanner;
public class Hemtenta {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int addcounter = 0;
int sum;
System.out.println("Welcome to 21");
System.out.println("The game revolves about you or your opponent getting to 21 ");
System.out.println("You both start on the same number 0, ");
System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
System.out.println("Think smart!");
while(counter <= 20) {
System.out.println("Please choose to add 1 or 2");
addcounter = input.nextInt();
counter += addcounter;
System.out.println("We are now on a total of " + (counter));
}
if (counter==21) {
System.out.println("Congratulations x! you won");
}
else {
System.out.println("Something went wrong! Try again");
}
}
}
You could look towards adding a
while (addcounter != 1 && addcounter != 2) {
// Prompt for values
}
To check that the value input by the user is either a 1 or a 2. If it isn't, then don't accept it and continue prompting till a valid input is registered.
And a
int turnCounter = 0;
...
// Within the loop
turnCounter += 1;
...
// At the end
if (turnCounter % 2 == 0) {
//Player Y wins
} else {
//Player X wins
}
To identify the turns, since turn 1s will be by player X, and turn 2s will be player Y. All turns by player Y will be in multiples of 2.
Problem statement
I have another thread on this, but I can't seem to locate it. Basically, I have a Black Jack game. The user is given two random cards (then those cards are added together, and display the total). Then it prompts user if they want another card (They pretty much will want to have a total lower than 21). If they choose "yes," they are given a random card number (they can keep getting a card, but should avoid going over 21), but if they choose "no," the game stops.
Here's the output I should get: [blackjackoutput.jpg]
And here's what I'm getting: [output1.jpg]
Source code:
public class BlackJackGame {
public static void main(String[] args) {
int randomnum1 = (int) (1 + Math.random() * 10);
int randomnum2 = (int) (1 + Math.random() * 10);
int total;
char anotherCard = 'y';
char playAgain;
Scanner input = new Scanner(System.in);
// Prints cards player starts off with
System.out.println("First cards: " + randomnum1 + ", " + randomnum2);
// Sum of the 2 cards
total = randomnum1 + randomnum2;
// Prints Total
System.out.println("Total: " + total);
// Do While Loop that asks question to get lower than 21 or terminate.
while (anotherCard != 'n') {
if (total <= 21) {
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
int randomnum3 = (int) (1 + Math.random() * 10);
System.out.println("Card: " + randomnum3);
total += randomnum3;
System.out.println("Total: " + total);
} else if (total > 21) {
System.out.println("BUST.");
System.out.print("Would you like to play again? (y/n): ");
playAgain = input.next().charAt(0);
}
}
}
}
Issue
When I reach to 21, I choose "no," to stop the program. But, it continues to display the next card and the updated total.
When I "BUST." (Or go over 21). It'll ask me if I want to play. And on separate occasions, I choose "y" and it says "Bust." and asks me if I want to play again (it loops, says "BUST.", and asks me the same question, without being able to end the program). Same thing if I choose "no" it'll say "Bust." and ask me if I can want to play again.
How do you play the game again?
PLEASE HELP!!!
The issue you have is a logic issue here:
if (total <= 21)
{
System.out.print("Do you want another card? (y/n): "); //<--------------
anotherCard = input.next().charAt(0);
int randomnum3 = (int) (1 + Math.random() * 10);
System.out.println("Card: " + randomnum3);
total += randomnum3;
System.out.println("Total: " + total);
You need to check if(anotherCard == 'n') to break out of the loop
Side Note
This blackjack game should have a better distribution of random cards better modeled off a 52 card deck