&& and || in while loop problems - java

I have been assigned to make a dice game of high or low for my intro to java course. I have all the methods completed, however, I need to use a while loop so that I can continue to play the game until my cash hits 0 or if I bet 0 dollars. I do not want to use a break if I do not have to. So my question is what can I do (if possible) to just only use the while loop? Here is my program:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int cash = 100;
int bet = 1
while(cash > 0 || bet != 0)
{
bet = getBet(in, cash);
char choice = getHighLow(in);
int roll1 = getRoll();
System.out.println("Dice 1 rolls: " + roll1);
int roll2 = getRoll();
System.out.println("Dice 2 rolls: " + roll2);
int total = (roll1 + roll2);
System.out.println("The total roll is: " + total);
int winnings = determineWinnings(choice, bet, total);
cash = cash + winnings;
}
System.out.println("You have " + cash + " dollars left. Goodbye!");
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
System.out.println("You have " + currentPool + " dollars");
System.out.println("Enter and amount to bet (0 to quit): ");
int bet = inScanner.nextInt();
while (0 > bet || currentPool < bet )
{
System.out.println("Your bet must be between 0 and " + currentPool + " dollars ");
bet = inScanner.nextInt();
}
return bet;
}
// Given a Scanner, prompt the user for a single character indicating whether they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should accept
// either capital or lowercase answers, but should display an error if the user attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
inScanner.nextLine();
char choice = inScanner.nextLine().charAt(0);
choice = Character.toUpperCase(choice);
while (choice != 'H' && choice != 'L' && choice != 'S')
{
System.out.println("You must choose between high, low or sevens (H/L/S): ");
choice = Character.toUpperCase(inScanner.nextLine().charAt(0));
}
return choice;
}
// Produce a random roll of a single six-sided die and return that value to the calling
// program
private static int getRoll() {
Random generate = new Random();
int roll = generate.nextInt(6) + 1;
return roll;
}
// Given the choice of high, low or sevens, the player's bet and the total result of
// the roll of the dice, determine how much the player has won. If the player loses
// the bet then winnings should be negative. If the player wins, the winnings should
// be equal to the bet if the choice is High or Low and 4 times the bet if the choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
if(roll <= 6)
{
if(highLow == 'L')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
else if (roll == 7)
{
if(highLow == 'S')
{
System.out.println("You won " + (bet * 4) + " dollars! ");
return (bet * 4);
}
else
System.out.println("You lose! ");
return -bet;
}
else
{
if(highLow == 'H')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
}
}

Change the while(cash > 0 || bet != 0) to while(cash > 0 && bet != 0)
This is because, you want to end the game if either cash equals 0 or when bet equals 0. If you use the || then only when both variables are 0 will the loop stop. If you use the && then the loop will stop if either of the variables are 0.
when && is used, both conditions must be true for the loop to execute. If one condition is true and the other is false then, the loop will stop.
when || is used, any one
condition must be true for the loop to execute. If both conditions are true the the loop will run. If one of the conditions is false and the other is true then, it will still run. If both conditions are false then, the loop will stop.
EDIT:
If you want the program to end as soon as the bet variable is 0 then just add these lines after bet = getBet(in, cash);:
if(bet<=0){
System.out.println("You are out of cash!");
break;
}
Hope this helped:)

Related

My "Else If" Code Isn't Working As Expected

I am a new coder. Working on an assignment. This is also my first post here so I apologize if it's a little sloppy.
I'm having some troubles with my if/else statements in Java...the "if" conditions seem to work okay. But my "else" conditions do not. Take a look at the code and the build results below.
Basically, I enter an ingredient. And then I put in the number of cups needed. And the number of calories the ingredient has per x cup. That all seems to work as long as I input what I want to for "successful" results.
Successful Build Image
But when I start to input values outside of my criteria, my application doesn't seem to care. If I input 0, I should get that output of "your response is invalid" or whatever it is I coded. But it just seems to skip over that entirely.
Bad Code Image
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 || numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Problem was in line:
if (numberCups >= 1 || numberCups <= 100) {
...
}
When you entered 0, program checked if 0 is greater or equal to 1, and that was false but you had also "or" condition ( || ), and in that condition you were checking if 0 <= 100 and because that is true, false || true gives true and that's why your if statement was correct. You needed to use "and" ( && ) instead of "or". There was flaw in your logic.
Test code below, it should work now:
package recipe_collection_manager;
import java.util.Scanner;
public class Ingredient {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
//Initializes the variables
String nameOfIngredient = "";
int numberCups = 0;
int numberCaloriesPerCup = 0;
int totalCaloriesPerCup = 0;
double totalCalories = 0.0;
// Enter the name of the ingredient.
System.out.println("Please enter the name of the ingredient: ");
nameOfIngredient = scnr.next();
// Enter the number of cups needed for the ingredient.
// If Else statements used to establish if the number of cups is valid.
System.out.println("Please enter the number of cups of "
+ nameOfIngredient + " we'll need. The number of cups must be between 1 and 100: ");
numberCups = scnr.nextInt();
if (numberCups >= 1 && numberCups <= 100) {
System.out.println("The number of cups is valid.");
} else if (numberCups <= 1 || numberCups >= 100) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Enter the number of calories used per cup.
// If Else statements are used to establish if the number of calories is valid.
System.out.println("Please enter the number of calories per cup: ");
numberCaloriesPerCup = scnr.nextInt();
if (numberCaloriesPerCup >= 1 || numberCaloriesPerCup <= 1000) {
System.out.println("The number of calories is valid.");
} else if (numberCaloriesPerCup <= 1 || numberCaloriesPerCup >= 1000) {
System.out.println("The number you have entered is invalid. Please try again.");
}
// Calculation for totalCalories based on numberCups and numberCaloriesPerCup
if (numberCups > 0 && numberCaloriesPerCup > 0) {
totalCalories = numberCups * numberCaloriesPerCup;
}
System.out.println(nameOfIngredient + " uses " + numberCups
+ " cups and has " + totalCalories + " calories.");
}
}
Just to clarify. The following statement
if(numberCups >= 1 || numberCups <= 100) {
...
}
Is true any number of cups. Any number of cups >= 1 will be caught by the first condition. Any number of cups <= 0 will be caught by the second condition since in that case they will all be less than 100. With a logical || only one condition is required to be true for the statement to be true.
In fact,
if(numberOfCups is >= A || numberOfCups <= B) {
...
}
will always be true as long as B >= A-1.

How do I use the "return" value of one method in another method

I am currently working on this project that plays the high low dice game. I am stuck on how to use the returned char from getHighLow and the returned int from getBet and getRoll in determineWinnings. This is my first year learning Java currently, so any help would be appreciated. Thank you in advance for any help you can give!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int currentPool = 100;
getBet(keyboard, currentPool);
getHighLow(keyboard);
getRoll();
>> determineWinnings(highLow, userBet, rollSum);
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
int userBet = -1;
while (userBet == -1) {
inScanner = new Scanner(System.in);
System.out.println("You have $" + currentPool);
System.out.println("Enter an amount to bet (0 to quit): ");
userBet = inScanner.nextInt();
if (userBet > currentPool || userBet < 0) {
System.out.println("Your bet MUST be between 0 and " + currentPool + " dollars");
userBet = -1;
}
if (userBet == 0) {
System.out.println("You have " + currentPool + " dollars left.");
System.out.println("Goodbye!");
}
}
return userBet;
}
// Given a Scanner, prompt the user for a single character indicating whether
// they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should
// accept
// either capital or lowercase answers, but should display an error if the user
// attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
Scanner keyboard = new Scanner(System.in);
int i = 0;
String userChoice = "";
while (i == 0) {
System.out.println("High, low or sevens (H/L/S): ");
userChoice = keyboard.nextLine();
if (userChoice.length() > 1 || (userChoice.charAt(0) != 'H' && userChoice.charAt(0) != 'h'
&& userChoice.charAt(0) != 'L' && userChoice.charAt(0) != 'l' && userChoice.charAt(0) != 'S'
&& userChoice.charAt(0) != 's')) {
System.out.println("ERROR: You must type H, L, or S.");
} else {
i++;
}
}
char highLow = 'N';
if (userChoice.charAt(0) == 'H' || userChoice.charAt(0) == 'h') {
highLow = 'H';
} else if (userChoice.charAt(0) == 'L' || userChoice.charAt(0) == 'l') {
highLow = 'L';
} else {
highLow = 'S';
}
return highLow;
}
// Produce a random roll of a single six-sided die and return that value to the
// calling
// program
private static int getRoll() {
int dieOne = (int) (Math.random() * 6 + 1);
System.out.println("Die 1 rolls: " + dieOne);
int dieTwo = (int) (Math.random() * 6 + 1);
System.out.println("Die 2 rolls: " + dieTwo);
int rollSum = dieOne + dieTwo;
System.out.println("The total of two dice is: " + rollSum);
return rollSum;
}
// Given the choice of high, low or sevens, the player's bet and the total
// result of
// the roll of the dice, determine how much the player has won. If the player
// loses
// the bet then winnings should be negative. If the player wins, the winnings
// should
// be equal to the bet if the choice is High or Low and 4 times the bet if the
// choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
int highLowValue = 0;
int winnings = 0;
if (highLow == 'H') {
highLowValue = 8;
} else if (highLow == 'L') {
highLowValue = 6;
} else {
highLowValue = 7;
}
if (roll >= 8 && highLowValue == 8) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll <= 6 && highLowValue == 6) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll == 7 && highLowValue == 7) {
winnings = bet * 4;
System.out.println("You won " + winnings + " dollars!");
} else {
winnings = -1 * bet;
}
return winnings;
}
You can assign the output of each method to variable or call methods directly on determineWinnings.
plan 1)
int userBet = getBet(keyboard, currentPool);
char highLow = getHighLow(keyboard);
int roll = getRoll();
determineWinnings(highLow, userBet, roll);
plan 2)
determineWinnings(getHighLow(keyboard), getBet(keyboard, currentPool), getRoll());
There are following approaches to get the result of one method to another.
Pass result of one method to another
Define private/static members
Better way would be passing result of one method to another method.

How can I complete my number guessing game?

My program should execute these steps:
Generate random no from 0 to 100.
Display random no and ask user enter (h/l/c)? (user have to enter one of them).
If it is correct ask user if they like to play again (y/n)? (user must answer (y/n))
I was able to execute Question no.1. Question no.2, random no display but I am unable to type character (h/l/c). Also, I am not able to ask player if they want to play again or not?
Here is what I have done:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
Your program does not accept any user input about if the guess is too low or too high.
You declared "answer" with an equation so it should accept a number.
answer would require a char or String value.
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String

Working on Loop-iterations. Is there a way to call these methods and not have several "do" declarations

//Setting my variables.
Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;
//Loop iterations to resolve error, and determine value for each input.
do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();
if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);
do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();
if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}
So, this is my code. I'm experimenting with loops, and if-else type statements. I feel like, MY approach is way to complicated and could be easily summarized or revised period. Does anyone know how to approach with, with only declaring one do statement? This code is just in the beginning phases of my experiment and has much work to do. But before I move on, I was hoping for another set of eyes!
Use of infinite loop with break on valid input. Enhanced to handle bad input.
Scanner keyboard = new Scanner(System.in);
int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");

How to make int counter go down when answer is wrong

Im making a player 2 guesses player 1's number game. Ive made an int counter thats == 10 and is meant to go down everytime player 2 gets answer wrong. I cant get it to work and i need help on how to make this. Youll see what i mean...
package guessMain;
import java.awt.*;
import java.util.Scanner;
public class GuessCodeSource {
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else if (answer <= 100){
System.out.println("Guess in the space below.");
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
}else if (guess != answer);
for (int counter = 10; counter-=1);
System.out.println("You have " + count + " of guesses left");
}
}
}
To make reduce a number by one, use the decrement operator.
For example,
counter--;
would subtract one from the counter.
If you want to subtract more than one, you can use the "-=" operator in the following manner:
counter -= 2;
So, in your code, in the final else if block, you could change the code to the following to reduce "counter" by 1.
else if (guess != answer) {
counter--;
System.out.println("You have " + count + " of guesses left");
}
But, in your code, you never declare the variable counter. Somewhere, most likely at the top of your code, you want to create this variable. To create an Integer variable you do the following:
int counter = 10;
You asked how to LOOP as well, so here it is. Read the comments to gain understanding of what the code does. If you have more questions, ask below.
public static void main(String[] args) {
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
int guess = 0; // Create these variables up here to access them everywhere in "main"
int counter = 0;
boolean continueTheGame = true; // A boolean variable that holds ONLY either true or false
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
// A while loop will continue as long as a boolean expression is true.
// So, we create a boolean variable somewhere above called "continueTheGame"
// As long as this is true, the code INSIDE of the while loop's brackets will repeat.
// If the user has less than zero guesses left, we can set the variable to false,
// which will make the loop stop!
while (continueTheGame == true) { // The start of the while loop
if (answer >= 100) {
System.out.println("BUSTED! I said a number between 1 - 100!");
} else if (answer <= 100) {
System.out.println("Guess in the space below.");
guess = josh.nextInt();
}
if (guess == answer) {
System.out.println("CORRECT!!!!!");
} else if (guess != answer) {
counter--;
System.out.println("You have " + counter + " of guesses left");
if (counter > 0) { // If they have MORE than zero guesses left, loop again!
continueTheGame = true;
} else { // If they have zero guesses left, make it stop looping
continueTheGame = false;
}
}
}
// Once the loop ends, the code will start again here,
// because the bracket above is the final bracket of the WHILE loop
}
Okay, so here is the full functional main method you are looking for:
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else {
System.out.println("Guess in the space below.");
}
for (int count = 10; count>=0; count--) {
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
System.exit(0);
} else {
System.out.println("You have " + count + " of guesses left");
if (count == 0) {
System.out.println("Sorry, you lost, no more tries..");
System.exit(0);
}
}
}
josh.close();
}

Categories

Resources