Using a loop to figure out the number of tries left - java

I have this celebrity guessing game where the user has to guess a celebrity’s name, given only a portion of the letters in the name.
I give the player the “clue” (e.g.rge oney) and read in their guess. The program should have a loop that allows them to keep guessing. If they guess incorrectly 3 times, give them a hint If they guess incorrectly a fourth time (after the hint), they lose the game (and you should tell them who the celebrity was).
I'm having trouble with the loop. this is what I have so far.
System.out.println("Celebrity Guessing Game");
String celeb = "John Lennon";
System.out.print("Choose your difficulty (easy/medium/hard): ");
String difficulty = input.nextLine();
int maxtry = 3;
if (difficulty.equals("easy"))
{
System.out.println("Here is your clue: " + celeb.substring(1, 4) + " " + celeb.substring(5,10));
}
else if (difficulty.equals("medium"))
{
System.out.println(("Here is your clue: " + celeb.substring(0, 3) + " " + celeb.substring(4,9)));
}
else if (difficulty.equals("hard"))
{
System.out.println(("Here is your clue: " + celeb.substring(2, 4) + " " + celeb.substring(5,7)));
}
System.out.print("What is your guess? ");
String guess1 = input.nextLine();
System.out.println("guess1 = " + guess1 + " celeb = " + celeb );
while (!guess1.equals(celeb) && maxtry == 3 ) {
if (!guess1.equals(celeb) && maxtry == 3) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
if (guess1.equals(celeb) || guess1.equals("john lennon")) {
System.out.println("Good Guess, you are correct!");
}
This is my output:
Celebrity Guessing Game
Choose your difficulty (easy/medium/hard): easy
Here is your clue: ohn Lenno
What is your guess? john lennon
guess1 = john lennon celeb = John Lennon
Try Again. Number of guesses left : 2
Good Guess, you are correct!
^ Why is it going through both if statements??

The problem is in checking condition. It have following problems:
It should be maxtry > 0 instead of maxtry == 3
Instead of equals() use equalsIgnoreCase()
Following is corrected code snippet:
while (!guess1.equalsIgnoreCase(celeb) && maxtry > 0 ) {
if (!guess1.equalsIgnoreCase(celeb) && maxtry > 0) {
maxtry--;
System.out.println("Try Again." + " Number of guesses left : " + maxtry);
}
Note: You are not reading input from user for other tries.

Related

If Statement Not Returning an Output

I am finishing an assignment for Introduction to Java and have been stuck for hours.
When I run the code below, enter the integers and hit enter, I do not get anything in the output. Please help!
import java.util.Scanner;
public class U3A1_DebugFixIFStmts {
public static void main(String[] args) {
System.out.println("If Statements");
Scanner input = new Scanner(System.in);
// Prompt User to Enter Three Integers
System.out.print("Enter three integers: ");
int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();
//Determine & print the state of choices made
if (firstChoice == 0)
{System.out.println("State of choices: \n" +
"no choices made yet");}
else if (secondChoice == 0)
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"number of choices = 1");}
else if (thirdChoice == 0)
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"user made second choice (" + secondChoice + ")\n" +
"number of choices = 2");}
else
{System.out.println("State of choices: \n" +
"user made first choice (" + firstChoice + ")\n" +
"user made second choice (" + secondChoice + ")\n" +
"user made third choice (" + thirdChoice + ")\n" +
"number of choices = 3");}
}
}
int firstChoice = input.nextInt();
int secondChoice = input.nextInt();
int thirdChoice = input.nextInt();
These three lines of your codes require your input before your program moves ahead. Hence, give 3 numbers and then you'll see it work.

java - issue with double, when user enter letter/signs, the program fails to run

I am a beginner and I am trying to make a simple calculator program using double variables, so that it allows users to add both int and double numbers to calculate. But whenever the user enters a String, the program fails. I have tried a lot to resolve this simple issue. I hope someone can help me.
Please enter first number: So when the user enters 25/25.5 everything works, but when user enters a letter such as e/f/k etc, the program fails. I have tried the following code after "Please enter first number":
if (user1 == aswin.nextDouble())
{
System.out.println("Continue");
}
else (user1 == Double.parseDouble(str))
{
System.out.println("Invalid Entry - Please enter Only numbers");
}
Following are the actual program, without the above code:
import java.util.Scanner;
import java.text.NumberFormat;
public class NewTwo_Calculator_IF_Statement {
public static void main (String [] args)
{
Scanner aswin = new Scanner (System.in);
double user1 = 0, user2 = 0, mult, div, sub, ad;
char user3;
boolean run = true;
String user;
System.out.println ("Welcome to ASWINS calculator" + '\n');
System.out.print ("Please enter First number - ");
user1 = aswin.nextDouble();
System.out.print("Please Enter Second number - ");
user2 = aswin.nextDouble();
System.out.println ('\n' + "Please choose following options" + '\n');
System.out.println ("Type either A/a/+ for Addition ");
System.out.println ("Type either S/s/- for Substraction");
System.out.println ("Type either D/d or / for Division ");
System.out.println ("Type M/m/* for Multiplication");
user3 = aswin.next().charAt(0);
mult = user1*user2;
ad = user1+user2;
sub = user1-user2;
div = user1/user2;
if (user3 == ('*') || user3 == ('m') || user3 == ('M'))
{
System.out.println('\t' + "Multiplication of " + user1 + " and " +user2 + " is = " + mult + '\n');
} else if (user3 == ('+') || user3 == ('a') || user3 == ('A'))
{
System.out.println ('\t' + "Addition of " + user1 + " and " +user2 + " is = " + ad + '\n');
} else if(user3 == ('-') || user3 == ('s') || user3 == ('S'))
{
System.out.println ('\t' + "Substraction of " + user1 + " and " +user2 + " is = " + sub + '\n');
} else if (user3 == ('/') || user3 == ('d') || user3 == ('D'))
{
System.out.println ('\t' + "Division of " + user1 + " and " +user2 + " is = " + div + '\n');
} else
{
System.out.println('\t' + "Invalid Input");
}
System.out.println ("Please Enter 'e' or type 'exit' to exit the program OR type anything else to stay on the page" + '\n');
user = aswin.next();
if (user.equalsIgnoreCase("e") || (user.equalsIgnoreCase("exit")))
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println ("You QUIT the page, Thanks and Hope you will use my(Aswin's) Calculator again");
System.exit(0);
}
else
{
System.out.println("Thanks for Entering -> " + user + " <-");
System.out.println (" You are STAYING on the page, Thanks " + '\n');
System.out.println ( "Thank you so much for using my calculator");
}
}
}
On the official documentation, it is mentioned that .nextDouble() throws a InputMismatchException when the next token (user input) does not match a float (such as when the user inputs a letter). You can handle such exception by using a try catch block:
try{
user1 == aswin.nextDouble()
}catch(InputMismatchException e){
// User input is invalid
System.out.println("Invalid Entry - Please enter Only numbers");
}
You can read more about catching and handling exceptions here.

if/else statement inside of a while loop

I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}

JAVA, How to restart my program from the start?

I am new to Java and I am doing some exercises, I created an if statement and else if so that when the user clicks 2 it will start the program from the start.
The problem is at the else if (yesNo == 2), I don't know what kind of code should I write there to start the program from the start. Can anybody help me? thank you.
if (option == 1) {
System.out.println("1: DAF");
System.out.println("2: Mercedes-benz");
model = in.nextInt();
if (model == 1) {
System.out.println("Model: " + mixer2.getModel());
System.out.println("Age: " + mixer2.getAge());
System.out.println("Cost: " + mixer2.getCost());
System.out.println("Capacity: " + mixer2.getCapacity() + " squares meters");
System.out.println("For how long do you want the vehicle to hire?, maximum is 12 months and every month cost 4000");
hireVehicle = in.nextInt();
cost = 4000 * hireVehicle;
System.out.println("The total cost is " + cost + " Do you want to proceed?");
System.out.println("1: yes");
System.out.println("2: no");
yesNo = in.nextInt();
if (yesNo == 1) {
System.out.println("Now, please enter your first name to complete the contract");
String name = in.next();
System.out.println("CUSTOMER CONTRACT");
System.out.println("Customer name: " + name);
System.out.println("Duration: " + hireVehicle + " months");
System.out.println("Date: " + date.date1());
}
else if (yesNo == 2){
}
You could use a loop like this one :
boolean repeat = True;
while (repeat)
{
if (yesNo ==1)
repeat = False;
else if (yesNo == 2)
repeat = True;
}
It might be easier with a do while loop, but i heard they're dirty

How to conditionally loop a statement using if in Java?

I just started learning Java in a class. The assignment was to make a Rock, Paper and Scissors game, here is my source code. I turned this in already but have not received a grade.
package rockpaperscissors;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create scanner input
Scanner input = new Scanner (System.in);
// Introduce user to game
System.out.println("Welcome to the Rock, Paper and Scissors game");
// Ask the user for their move
System.out.println("\nPlease select a move\nEnter 0 for Scissors, 1 "
+ "for Rock and 2 for Paper");
int userMove = input.nextInt();
// Ensure that userMove is between 0 and 2
if (userMove > 2 || userMove < 0) {
System.out.println("Invalid entry the result of this game will not "
+ "be accurate! Please retry using either 0 for Scissors, 1"
+ " for Rock and 2 for Paper\n");
}
// Generate computerMove using java.util.Random
// Create instance first
Random MyRandom = new Random();
//Now generate number
int computerMove = MyRandom.nextInt(3);
System.out.print("The computer played " + computerMove + "\nRemember"
+ " 0 stands for Scissors, 1 is for Rock and 2 is for paper\n");
// Determine draw result
if (userMove == computerMove) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The game is a draw!");
}
// Determine computer win
else if(userMove == 0 && computerMove == 1) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
else if(userMove == 2 && computerMove == 0) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
else if(userMove == 1 && computerMove == 2) {
System.out.println("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " The Computer Wins!");
}
/* Determine User win, as no other moves can result in computer win all
other combinations will result in user win
*/
else {
System.out.print("\nYou played " + userMove + ", The computer "
+ "played " + computerMove + " You Win!");
}
}
}
I am having trouble on getting the program to re-ask for a number if the number is above 2 or below 0, it will say "Invalid entry the result will not be valid..." but it will still preform the rest of the program with an invalid number.
How can I make the program stop and prompt the user for a valid number and then preform the program? Additionally, this is the third program I have ever made so any other advice would be appreciated.
Thanks
What you want is to not do all the other code if your conditions are met.
Right now you are giving an error message when your conditions are met - but not stopping execution of the rest of the function.
you can just stop.
So - without telling you the exact answer... how do you exit from a function?
Do that just after the error message gets displayed and you will be fine.
However - if you want to continue fetching the user input until you meet the conditions... that requires a loop around the part that fetches and checks.
what loops do you know?
do you know one that lets you loop until you've met some condition?
you've got your condition already... now you just need to adapt a loop to let you do the code that you want - repeatedly - until that condition is met.
in pseudo code (ie this is not real java - you must translate):
some_loop do
fetch user input
give error message if its not ok
until (user input is ok)

Categories