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

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.

Related

using a while loop for user to input multiple int and find the max and min

so my homework question is prompt user a series of integers and find the max and min of those integer. Use a loop and -99 to break loop.Below is my code but my question is that is there a shorter way for this? feel free to comment and i appreciate your time reading this.
Scanner input=new Scanner(System.in);
int num1,num2,max,min;
System.out.print("enter a number: ");
num1=input.nextInt();
System.out.print("enter another number: ");
num2=input.nextInt();
max=Math.max(num1,num2);
min=Math.min(num1,num2);
while (num2!=-99){
System.out.print("enter a number or -99 to stop: ");
num2=input.nextInt();
if(num2!=-99){
max=Math.max(max,num2);
min=Math.min(min,num2);
}
}
System.out.println("largest is: "+max);
System.out.println("Smallest is: "+min);
You check for the condition of num2 != -99 twice, remember the first rule of programming, do not repeat yourself
You could save some lines by checking for min and max before asking for the next input. This way you do not need to check if num2 != -99 inside the while loop
Ok So after working on this. I finally did it. It does have a small bug, but I really don't wanna fix it so if anyway wants to edit this then be my guest.
Scanner input = new Scanner(System.in);
int studentNum = 0;
ArrayList<Integer> calc = new ArrayList<Integer>();
while (studentNum <= 100) {
System.out.print("Enter a number: ");
calc.add(input.nextInt());
studentNum += 1;
if (input.nextInt() == -99) {
break;
}
}
int min = Collections.min(calc);
int max = Collections.max(calc);
for (int i = 0; i < calc.size(); i++) {
int number = calc.get(i);
if (number < min)
min = number;
if (number > max)
max = number;
}
System.out.println("Max is " + max);
System.out.println("Min is " + min);
This does exactly what you want. However, there was a problem checking for the exit signal.
if (input.nextInt() == -99) {
break;
}
this checks if the userInput is equal to -99 then stops the program and calculates and prints out the min and max. However the tiny bug is that it will first ask for your number to add to the array list and then it will ask again for the userInput to check if its equal to -99. But overall it does exactly what you want.
Hope this helped.
EDIT I will work on it later and find a way to fix that bug if no one else knows.
Your code has one minor bug and can be slightly optimised. Things you might want to consider:
What happens (and what should happen) when the user types -99 as the second number?
Do you necessarily need to have at least 2 numbers? Wouldn't one be enough for the program to exit gracefully? The first number would then be both min and max.
Can you re-order your code lines so that the duplicated (num2!=-99) is not necessary anymore?
Pro questions:
What happens if the user types in some letters? How can you handle that case?
What happens if the user types in a super high number (bigger than the maximal integer)?
What happens if the user presses enter without typing any number?
Nitpicking:
Using + to concatenate strings and numbers is a bad idea because it's hard to remember where it works and where it doesn't.
Better look into String.valueOf(int i) and String.format(String format, Object... args)
Look up Google's Java Coding Style for formatting your code in best readable way. In many editors you can automatically apply the style. It describes things like where to use spaces or what to indent.

Why is my while going in a infinity loop? How do I fix it?

I dont know why my do while is going on infinity and not showing my output which should be how many quaters, dimes ,etc has that amount of money that the user input in the system.
Scanner scan = new Scanner(System.in);
System.out.println("Enter the amount of money: ");
float dinero= scan.nextFloat();
int quaters=0;
int dimes =0;
int nickle =0;
int pennys =0;
boolean b=false;
do{
if(dinero>=0.25){
dinero=(float) (dinero-0.25);
quaters++;
}else if(dinero<0.25 && dinero>=0.10){
dinero=(float) (dinero-0.10);
dimes++;
}else if(dinero<0.10 && dinero>=0.05){
dinero=(float) (dinero-0.05);
nickle++;
}else if(dinero<0.05 && dinero<0){
dinero=(float) (dinero-0.01);
pennys++;
}else{
b=true;
}
}while(b==false);
System.out.println("Quater :"+quaters);
System.out.println("Dimes :"+dimes);
System.out.println("Nickle :"+nickle);
System.out.println("Pennys :"+pennys);
Please help i know this is a dumb question but help will be much apprishiated.
Not sure what you are trying to do but here is your problem: the last else is never executed because you covered all the possible cases in the if instructions before. Because of that, b will always be false and therefore your loop will go on forever. In which condition do you exactly want to exit this loop? Think about this and then move the instruction in the last else into the corresponding if block. Also, the if before that is not correct either. You probably meant:
if(dinero<0.5 && dinero>=0){
//do stuff
}
I fix it it was that my last condition was wrong. Also the while was wrong
else if(dinero<0.05 && dinero>=0.01){
// was the the fix for the last else if
while(dinero>0.01);
// and here is the while
change the condition of your else if statement to
else if(dinero<0.05 && dinero>0)

Asking the user to think of, and write down, a number between 1 and 1,000,000 in java

Hi guys so I'm working on writing a program that's asking a user to think of and write down a number between 1 and 1,000,000.
then it asks questions like "Is it greater than 500000?", and the user answers "Yes" or "yes" or "no or "NO", or "Got It!" now this where I'm stuck at. I don't know how to get it to ask that questions
this is the code i got so far :
import javax.swing.JOptionPane;
public class Questions {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, Questions");
String S = JOptionPane.showInputDialog("Enter a number between 1 and 1,000,000");
int i = 1000000;
if (i>500000){
}
}
how do i use JOptionPane.showInputDialog to ask questions and get answers ?
Any help is appreciated.
First of all, I strongly recommend debugging in the console until your logic is complete, then work on the GUI.
You are basically trying to implement a binary search, where the computer should get the answer right in log(N) guesses.
Here is some code to get you started. The GUI should be fairly straightforward. Read the appropriate Javadocs.
try (Scanner k = new Scanner(System.in);) {
String input;
int lo = 0;
int hi = 1000000;
int mid;
while (true) {
mid = (lo + hi) / 2;
System.out.printf("Is it equal to %d?\n", mid);
if (!input.equalsIgnoreCase("Got it!")) {
break;
} else {
System.out.printf("Is it greater than %d?\n", mid);
input = k.nextLine();
if (input.equalsIgnoreCase("yes")) {
lo = mid;
} else {
hi = mid;
}
}
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
You can use showConfirmDialog() to ask a yes or no question...Here is an example you would need to change the values as these are hard coded but you should be able to figure out how to put this in a loop and change values dynamically based upon user entry:
int answer = JOptionPane.showConfirmDialog(null, "Is 500,000 your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(answer == 1)
{
answer = JOptionPane.showConfirmDialog(null, "Is 500,000 less than your number?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
}
This way the user doesn't have to type "yes" or "no" or "got it" which will eliminate human error...
Yes - will return 0
No - will return 1
The second question will tell u whether there number is lower or higher than the proposed number depending on whether they answer yes or no...
First you should change S to an integer because you're asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I'm not quite sure what the exact syntax is for JOptipnPane but you can find commands for input and output):
String YesOrNo = JOptionPane.ShowInputDialog ("is the number higher than 500,000? ")
If YesOrNo.equalsIgnoreCase ("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest if not comment for further help
First you should change S to int because you are asking the user to enter an integer. Second, assuming the program is supposed to try to guess the number, you would start with 500,000 and keep guessing in halves until you get the entered number (it looks like you got this part). So here is an outline (I am not quite sure what the exact syntax is for JOptipnPane is but you can find commands for input and output):
String yesOrNo = JOptionPane.ShowInputDialog("is the number higher than 500,000? ")
If yesOrNo.equalsIgnoreCase("yes") then guess 750,00 next if no guess 250,000 next
This is an outline see if you can get the rest. If not comment for further help.

Game of dice in 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!

Program not displaying everything it's supposed to

I am writing an inventory program for a book store that is comprised of two classes and multiple methods within these classes.
The method I'm having the most trouble with is my purchase() method which is supposed to interactively process a purchase, update the array after the purchase, and display totals for items sold and total amount of money made that day.
The method is supposed to follow these 10 steps:
Ask the user to enter the ISBN number of the book they'd like to purchase.
Search the array for the object that contains that ISBN.
If the ISBN isn't found in the array, display a message stating that we don't have that book.
If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
When they enter a 0 for the ISBN, the Scanner is supposed to close
Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
Print the updated array.
Display a count of how many books were purchased, and how much money was made from the purchase.
But as my code is written, after the Program prompts me to enter an ISBN, nothing happens, it just continually lets me enter numbers with no additional output.
Here is the code I have for this method. I'm pretty sure it's probably an issue with my loop as I'm not very good with looping. Can anyone spot what I'm doing wrong?
public static Book[] purchase(Book[] books) {
int itemsSold = 0;
double totalMade = 0;
double price;
int copies;
String isbn;
Scanner input = new Scanner(System.in);
int desiredCopies = 0;
int index;
double total = 0;
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
String desiredIsbn = input.next();
for (index = 0; index < books.length; index++) {
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() > 0) {
System.out.println("How many copies of this book would you like to purchase?");
if (!books[index].getISBN().equals(desiredIsbn))
System.out.println("We do not have that book in our inventory.");
if (books[index].getISBN().equals(desiredIsbn) && books[index].getCopies() == 0)
System.out.println("That book is currently out of stock.");
desiredCopies = input.nextInt();
}
if (desiredCopies > books[index].getCopies())
System.out.println("We only have " + books[index].getCopies() + "in stock. Please select another quantity: ");
desiredCopies = input.nextInt();
books[index].setCopies(books[index].getCopies() - desiredCopies);
if (input.next().equals(0))
System.out.println("Thank you for your purchase, your order total is: $" + total);
input.close();
total = books[index].getPrice() * desiredCopies;
itemsSold += desiredCopies;
totalMade += total;
System.out.print(books[index]);
System.out.println("We sold " + itemsSold + " today.");
System.out.println("We made $" + totalMade + "today.");
}
return books;
}
Any help would be greatly appreciated.
You are not matching every possible condition
Your if statements aren't covering all the possible permutations of conditions apparently.
You should use always use an if/else if/else block to make sure you cover all your conditions. Outside this there is absolutely no way for anyone to provide any actual solution with so little to go on.
Also
Scanner and StringTokenizer are two of the worst designed classes in the JDK outside Date and Calendar. They cause endless trouble for new people and are avoided by the veterans.

Categories

Resources