Game of dice in java - java

The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.

You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.

As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!

Related

Java and Arrays

I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.

Hangman that saves wrong guesses in array and prints them before each guess. also prints gameboard with "_" and correct guesses

so I've been studying Java for about 3 months and I am supposed to do a Hangman code using only arrays, loops, and if statements. the word to be guesses is read from another file and saved as a string. I have to be able to save the wrong guesses in an array. and after each guess print all the wrong guesses so far, as well as the gameboard with underscores for not guessed letters and the correct guesses of course in their place. here is my code so far :
for(int l = 0; l<wordlength;l++)
{
System.out.print("_");
}
System.out.println();
System.out.println("WRONG: ");
for(int c = 0; c<numofGuesses;c++)
{
System.out.println();
System.out.print("GUESS"+guessN+"/"+numofGuesses+": ");
char guess1=in.next().charAt(0);
char guess = Character.toUpperCase(guess1);
guessN = guessN+1;
for (int j = 0; j<wordlength;j++)
{
if (guess==guessword.charAt(j))
{
System.out.println("Great guess!");
System.out.print (guessword.charAt(j));
}
else
{
System.out.print("_");
WRONG[u]=guess;
u++;
}
}
if you guess A it prints correctly "A___" but then if you guess B after instead of printing "AB__" (the word to guess is ABLE) i get "B__" also the wrong array is not storing and printing all the wrong guesses each time. please help I've been trying for 5 days and that's all I did the entire day today and I couldn't get past this.
Because this sounds a lot like a homework assignment, I will give directions for solving this, but not provide a full working solution. Hopefully, seeing how one could1 go about approaching such a problem is enough of a step in the right direction to be able to solve it yourself.
Let's first think about what we need to do.
Read a word that needs to be guessed, say String toBeGuessed.
You did this. ✔
Keep track of the characters the player has guessed so far.
Keep track of the number of turns a player has gotten.
Keep track of if the word has been guessed (player won!).
Say that the number of guesses a player can make is fixed. This can be modeled using a constant:
/**
* Number of guesses a player can take.
*/
public static final int NUM_GUESSES = 10;
Now let's think about the main logic of our hangman game. It is good to first think about the structure of your program and only later actually implement it. When thinking of the program structure, we don't bother with specifics of the programming language of your choice yet. In pseudocode, it would be something like the following, maybe (let's indicate what you already have with ✔).
for turn from 1 upto NUM_GUESSES do ✔
show player what they guessed so far
show the gameboard
ask player for their new guess ✔
save player's guess and update internal state
check if the player won, let them know if they did
if player did not win
let them know
Right. So, we need to somehow store the guesses that a player made. Every guess is a character, and we know there will be at most NUM_GUESS guesses in total. A good option (and one that is suggested by your exercise) is an array!
/**
* Characters that have been guessed so far.
*/
private char[] guessed;
This can be initialized as follows, since we know the maximum number of guesses:
this.guessed = new char[NUM_GUESSES];
This gives us an array of NUM_GUESSES characters that are initialized to 0 (see here). Since users won't guess that character, we can use it to represent guesses that have not been done yet. Alternatively, we can keep track of the current turn of the player in a separate variable. Your choice!
In the following, I will not keep track of the current turn in a separate variable, just to show more of arrays and loops. It might be a fun exercise to change this to using an int turn variable!
show player what they guessed so far
Alright, this should be fairly straightforward now. We basically need to print the part of the guessed array that is not 0. That can be done using a loop, like so for example:
System.out.print("You so far guessed: ");
for (int i = 0; i < guessed.length; ++i) {
if (i > 0) {
System.out.print(", ");
}
if (guessed[i] != 0) {
System.out.print(guessed[i]);
} else {
break; // stop the loop as soon as we run into a 0
}
}
System.out.println(".");
This will print something like You so far guessed: a, b, c. when the player guessed those characters. See how we only print the comma when some other character was printed before?
show the gameboard
The next point of the program structure is trickier to get right. Let's think a bit about structure again.
for each character in toBeGuessed
if the character has been guessed
print it
else
print an underscore
Looping over every character of a word can be done as follows.
int length = toBeGuessed.length();
for (int i = 0; i < length; ++i) {
char character = toBeGuessed.charAt(i);
// do something with character here
}
How do you find if a character has been guessed yet? Well, by checking if it is stored in the guessed array. This again can be done using a loop. That loop will be very similar to the one we have written above, when showing what the player guessed so far. I think you should be able to figure that one out.
save player's guess and update internal state
We move on to the next point of the program structure. Say that we have a char guess that the player guessed. We need to store this in our array guessed. Where? Well, at the first open spot, that seems a reasonable choice. To find that one, let's use a loop again, and break the loop when we have found an open spot.
for (int i = 0; i < guessed.length; ++i) {
if (guessed[i] == 0) {
guessed[i] = guess;
break;
}
}
check if the player won, let them know if they did
What we need to know in order to see if the player won, is simply if the number of characters they guessed right is equal to the number of characters in toBeGuessed. You could modify the loop for showing the gameboard to not print characters, but count correct ones. Then at the end compare to toBeGuessed.length() and if they are equal, the player won.
if player did not win, let them know
This should be fairly easy, if you got the previous point working.
When you did all the above and stitched it together, you should have a working version of hangman. Your very own, something to be proud of!
Some tips and tricks:
you can implement most of the points described above as separate methods;
when you do so, you can write one main method that calls the other methods (this will make it easier to read your own code and make changes to it);
try to put as little code as possible in the main method.
Here is a little template that you can start from.
import java.io.PrintStream;
import java.util.Scanner;
public class HangMan
{
/** Number of guesses a player can take. */
public static final int NUM_GUESSES = 10;
/** Word to be guessed in a game of hangman. */
private String toGuess;
/** Letters that have been guessed so far. */
private char[] guessed;
/**
* Construct a new game of hangman, ready to be played.
*/
public HangMan(String toGuess)
{
this.toGuess = toGuess;
this.guessed = new char[NUM_GUESSES];
}
// your other methods go here
/**
* Read guesses from given input and print results to given output.
* Continues until guesses have run out, or word was guessed.
*/
public void play(Scanner in, PrintStream out)
{
for (int round = 0; round < NUM_GUESSES; ++round) {
showGuessedSoFar(out);
showGameBoard(out);
char guess = askGuess(in, out);
saveGuess(guess);
if (hasPlayerWon()) {
out.println("You won!");
return;
}
}
// at this point, player ran out of guesses and hence lost
out.println("You lost...");
}
/**
* The bit that runs our hangman game.
*/
public static void main(String[] args)
{
// read word to guess from arguments, with a default value
// you would probably insert your "read word from file" code here
HangMan game = new HangMan(args.length >= 1 ? args[0] : "ABLE");
// play a game, using system input and output
game.play(new Scanner(System.in), System.out);
}
}
Good luck!
TL;DR. Trying to teach one how to think about a problem and how to write code that executes the solution one thought of. Features some example code with arrays and loops.
1 This is only one possible solution, there are always many ways to solve a given problem.

Implementing Java code for a betting game on coin-flips [closed]

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 6 years ago.
Improve this question
I have looked all over this website and other websites trying to figure how to do this with the knowledge that my teacher has provided me.
Basically the program is supposed to be a user input system where you can make bets on a head or tails coin flipping game.
So far, I've had no luck in what to do. Not asking someone to finish it for me, but to help me in the right direction.
Thank you in advance.
Here is my code so far:
package Homework6;
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int money = 10;
double flip = Math.random();
String heads = "heads";
String tails = "tails";
int bet = input.nextInt();
while(bet < 0 || bet > money){
if(true){
System.out.println("How much do you want to bet?");
input.next();
}
}
System.out.println("Guess if the coin will be heads or tails.");
String guess = input.next();
String coin;
if (flip <0.5) coin = heads;
else coin = tails;
if(guess == coin){
int correct = money + bet;
System.out.println("The flip was"+ coin);
System.out.println("You win" + bet);
System.out.println("")
}
}
}
To fix the possible infinite loop:
do{
System.out.println("How much do you want to bet?");
bet = input.nextInt();
}
while(bet > 0 && bet > money);
You can drop the if statement since it's not really needed. You will however need to declare the variable bet to have the correct scope.
if(guess.equals(coin)) // proper way of checking Strings
Use this form for checking the value of the guess vs the coin.
A few notes for you (since you're starting out and still a student):
1) Your while loop is a little bit poorly constructed. That System Out will constantly be printing to the screen until there is some input. And that if statement is essentially doing no conditional checking. It is always true.
2) You never originally prompt the user for how much they want to bet. You're only prompting them after they've input a value. So when you originally hit play, the console is just blank. But really it's waiting for some input.
3) Your if statement for changing the coin state is a little extraneous.
4) The user's amount of money is never actually updated, and the output at the end could be a little more informative.
5) What if someone wins the first one and wants to play again? They probably want to keep that bank growing! So you could encompass the entire thing inside of a do/while that runs while bank > 0.
6) You should only use the == operator when comparing primitive types. Pretty much all other times, use Object.equals(object);
I know you didn't ask someone to complete it for you, but this site works best by sharing information. Below should work for you, I've commented it extensively. Hopefully this can teach some things beyond just this homework assignment.
public static void main(String[] args)
{
// Setup some initial variables
int bank = 10;
double flip = Math.random();
// Instantiate a new Scanner object
Scanner input = new Scanner(System.in);
// Let the user bet until they run out of money in the bank
do
{
// Ask the user how much money to wager
System.out.println("How much do you want to bet?");
int bet = input.nextInt();
// The bet was invalid
while(bet < 0 || bet > bank)
{
System.out.println("Invalid bet (" + bet + "). Minimum bet = 0. Maximum bet = " + bank);
bet = input.nextInt();
}
// Ask the user for which side
System.out.println("Heads or tails?");
String guess = input.next();
// The coin is either heads or tails, so it can always start as tails. If the value goes under .5, change it to heads. If not, it remains the same, "tails".
String coin = "tails";
if (flip < 0.5)
{
coin = "heads";
}
// Tell the user the result, regardless of win or lose
System.out.println("The flip was " + coin);
// Update the user's bank and inform them of the new value
if(guess.equalsIgnoreCase(coin)) // this allows for any form of HeaDs or TaILs
{
bank += bet;
System.out.println("You win " + bet);
System.out.println("Your bank contains " + bank);
}
else
{
bank -= bet;
System.out.println("You lose " + bet);
System.out.println("Your bank contains " + bank);
}
}
while(bank > 0);
// Goodbye message
System.out.println("Thanks for playing!");
// Don't forget to close your Scanner object!
input.close();
}
Alright, since you are having so much trouble with this, I will lay it out how I achieved this.
You need a couple variables, I used these below, taken from your code.
Scanner input = new Scanner(System.in);
int money = 10;
String heads = "heads";
String tails = "tails";
int bet = 0;
String guess;
String coin;
You then need a loop. You have a while loop already, and that will do, BUT your conditional is incorrect as I see it. You are testing bet < 0 || bet > money which I read as "If you bet less than no money or bet more money that you have, enter this loop" I believe you want the opposite of that. I also added if you ran out of money.
while(bet > 0 || bet < money || money <= 0)
Now for the inside of the loop. Here, you want to do a couple things in a certain order.
Ask how much they want to bet, read it in the appropriate variable.
Ask what their guess is, read it in the appropriate variable.
Use your if statement you have to determine if the flip was heads or tails, But I got rid of the flip variable, and used Math.random() < 0.5 directly.
Check their guess vs the flip. If they were correct, do what you need to do, i.e. add bet to money and display some sort of message.
If they were wrong, do what you need to do, i.e. subtract bet from money, display some message.
Then your program will start over.

Codechef "Primality Test" Wrong answer

Problem:
Alice and Bob are meeting after a long time. As usual they love to play some math games. This times Alice takes the call and decides the game. The game is very simple, Alice says out an integer and Bob has to say whether the number is prime or not. Bob as usual knows the logic but since Alice doesn't give Bob much time to think, so Bob decides to write a computer program.
Help Bob accomplish this task by writing a computer program which will calculate whether the number is prime or not .
Input
The first line of the input contains T testcases, T lines follow
Each of T line contains an integer N which has to be tested for primality
Output
For each test case output in a separate line, "yes" if the number is prime else "no"
My solution:
`import java.io.*;
import java.math.*;
import java.util.*;
class ex6
{
public static void main(String args[])throws IOException
{
try
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int t=0;
t=Integer.parseInt(input.readLine());
int n=0;
int c=0;
while(c!=(t))
{
int j=0;
n=Integer.parseInt(input.readLine());
if(n==1)
System.out.println("No");
else{
for(int x=2;x<n/2;x++)
{
if(n%x==0){j++;break;}
}
if(j==0)
System.out.println("Yes");
else
System.out.println("No");
}
c++;
} }
catch(Exception e)
{return;}}}`
Your whole approach is wrong, read about https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. Besides, all these exercises assume that you use a known algorithm.
The idea is that you have an array with boolean values, where "true" means "prime" and "false" means "non-prime", what you do is start with an array of all true boolean values (besides 1 and 0), then starting with 2 eliminate the multiples of 2 (marking them false), then move to the next prime number, which is 3, mark false multiples of that, etc, until you're done.

Betting and Search for uniqueness

I've been working ahead in my intro class and I've almost finished my last project, Keno. its a betting game that rewards money according to how many numbers you matched with the dealer. I'm having issues on where to put the betting aspect, they start with 100$ and are asked to wage a certain amount of money. I don't know which method that would go under for it to still work because my methods aren't voids, so i wont be able to return more than one data value.
My second issue, maybe the more important one, is that they need to be unique numbers. To do that i would need to search the array of numbers every time to see if they match, or use an array of booleans to keep track of the numbers. I don't know how i would do the second but i have a good idea of what i would do with the first. The issue is that im using a do while already, im not sure how i could add the for loop with a nested for loop in. Here is my code, sorry if its messy, i know my teacher hates my curly braces:
package Keno;
import cs1.Keyboard;
public class Keno {
public static void main(String[]args){
int userArr[]=user();
int compArr[]=computer();
int howMany=matchNums(compArr,userArr);
int moneyGained=betting(howMany);
System.out.println("You matched "+howMany+" numbers");
System.out.println("You have gained "+moneyGained+" dollars!");
}
public static int[] computer(){
int []compChoice=new int[20];
for(int x=0;x<compChoice.length;x++){
compChoice[x]=(int)(Math.random()*81);
}
return compChoice;
}
public static int[] user(){
int choice[]=new int[7];
System.out.println("Welcome to Keno!");
System.out.println("Choose 7 unique numbers ranging from 1-80");
System.out.println("*************************************************");
//assigns numbers to choice array
for(int x=0;x<choice.length;x++){
do{
int temp=x+1;
System.out.println("number "+temp+": ");
choice[x]=Keyboard.readInt();
}while(choice[x]<0||choice[x]>80);
}
System.out.println("Thanks!");
System.out.println("*************************************************");
return choice;
}
public static int matchNums(int arr1[], int arr2[]){
int count=0;
//checks each array slot individually to see if they match
for(int x=0;x<arr1.length;x++){
for(int y=0;y<arr2.length;y++){
if(arr1[x]==arr2[y]){
count++;
}
}
}
return count;
}
public static int betting(int matches){
int moneyGained=0;
if(matches==7){
moneyGained=12000;
}else if(matches==6){
moneyGained=200;
}else if(matches==5){
moneyGained=20;
}else if(moneyGained==4){
moneyGained=1;
}
return moneyGained;
}
}
The simplest way to add the betting/money concept would be to add an integer which represents how much money the player has (starting at 100). You will have to ask the player how much they want to wager, and then adjust their money accordingly.
public static void main(String[] args) {
int playerMoney = 100;
int wagered = getWager(); // dont forget it has to be 0 < wagered <= 100
// adjust players money according to the wager, and how much they won
For ensuring uniqueness, either one of your ideas would work. I like just checking for the numbers existence already in the array, but the boolean array of size 80 would work too. It just seems like a lot for only 7 numbers though.

Categories

Resources