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
Related
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.
This question already has answers here:
Using variables outside of an if-statement
(2 answers)
Closed 2 years ago.
I'm a student and would like to know if there is a way to take a variable out of its scope block to be used in a local scope? I am trying to code a store of some sort where the users are given a few options to choose what they want to buy, how much they want to buy, and give them the total payment for the same Item. Now outside the block scope, I want to give the overall total with how much they bought of each item. Here's my code:
import java.util.Scanner;
public class SariSariStore{
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
int piattos = 20;
int wRabbit = 1;
int maxEM = 1;
int nescafeO = 7;
float iceW = 1.50f;
System.out.println("Would you like to buy something? [Y/N]");
char i = scanner.next().toLowerCase().charAt(0);
do {
System.out.println("==================================="
+"\n"+ "| Sari Sari Mart |"
+"\n"+ "==================================="
+"\n"+ "| What do you want to buy? |"
+"\n"+ "| |"
+"\n"+ "| 1) Piattos chips 20 Php |"
+"\n"+ "| 2) White Rabbit 1 Php |"
+"\n"+ "| 3) Max extra menthol 1 Php |"
+"\n"+ "| 4) Nescafe Original 7 Php |"
+"\n"+ "| 5) Ice water 1.5 PhP |"
+"\n"+ "| 6) Exit |"
+"\n"+ "===================================");
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
int itotal1 = piattos * quantity1;
System.out.println("Total price: " + itotal1 +" Php");
}else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
int itotal2 = wRabbit * quantity2;
System.out.println("Total price: " + itotal2 +" Php");
}else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
int itotal3 = maxEM * quantity3;
System.out.println("Total price: " + itotal3 +" Php");
}else if (choice == 4){
System.out.print("How many would you like to buy? " );
int quantity4 = scanner.nextInt();
int itotal4 = nescafeO * quantity4;
System.out.println("Total price: " + itotal4 +" Php");
}else if (choice == 5){
System.out.print("How many would you like to buy? " );
int quantity5 = scanner.nextInt();
float itotal5 = iceW * quantity5;
System.out.println("Total price: " + itotal5 +" Php");
}else if (choice == 6){
}
}else{
System.out.println ("Sorry we do not have that item, please pick among the choices");
}
int Total = itotal1 +itotal2 +itotal3 +itotal4 +itotal6; // problematic statement
System.out.println ("Your total is:"+ Total + " Php");
System.out.println ("Do you still want to buy something? [Y/N]");
i = scanner.next().toLowerCase().charAt(0);
}while (i == 'y');
if (i =='n'){
System.out.println("Thank you! Please come again");
}
}
}
Thanks :>
Can't you use just one field for this? Like this:
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
int total = 0;
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
total = piattos * quantity1;
System.out.println("Total price: " + total +" Php");
} else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
total = wRabbit * quantity2;
System.out.println("Total price: " + total +" Php");
} else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
total = maxEM * quantity3;
System.out.println("Total price: " + total +" Php");
}
...
} else {
System.out.println ("Sorry we do not have that item, please pick among the choices");
System.out.println ("Your total is:"+ total + " Php");
}
Also consider using switch statement for multiple if statements
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
You are using the wrong operator. != checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory).
You must write while (! "no".equals(proceed) ).
I did not write while (! proceed.equals("no") ) on purpose because if the string is null then you would get a NullPointerException.
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the "reverse" way as in my first example is more safely in general.
For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
You have to use .equals(String) to compare Strings, like so:
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (!proceed.equals("no")){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
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.
I have been trying to figure out how to make it so players could choose to restart the game at the end, but whenever I try to restart the loop, it says
Label Game was not found
even though it is clearly shown in this code.
// System objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
int enemyDeaths = 0;
List scores = new ArrayList();
// Player variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
boolean running = true;
System.out.println("Welcome to the Dungeon!");
Game:
while(running) {
System.out.println("-----------------------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while(enemyHealth > 0) {
System.out.println("\tYour HP: "+ health);
System.out.println("\t" + enemy + "'s HP:" + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink Health Potion");
System.out.println("\t3. Run");
String input = in.nextLine();
if(input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt + " damage. ");
System.out.println("\t> You received " + damageTaken + " in retaliation");
if(health < 1) {
System.out.println("\t> You have taken too much damage! You are too weak to go on!");
break;
}
}
else if(input.equals("2")) {
if(numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP"
+ "\n\t> You have " + numHealthPotions + " health potions left.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
else if(input.equals("3")) {
System.out.println("\tYou ran away from the " + enemy + "!");
continue Game;
}
else {
System.out.println("\tInvalid Command");
}
}
if(health < 1) {
System.out.println("You limp out of the dungeon, weak from battle");
break;
}
enemyDeaths++;
System.out.println("-----------------------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
System.out.println(" # Your current score is " + enemyDeaths * 100 + " # ");
if(rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! #");
System.out.println(" # You have " + numHealthPotions + " health potion(s). # ");
}
System.out.println("-----------------------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("2. Exit Dungeon");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid Command");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
scores.add(enemyDeaths * 100);
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
String randomWords;
in = new Scanner(System.in);
System.out.println("Enter a name to be remembered by");
randomWords = in.next();
scores.add(randomWords + " " + enemyDeaths * 100);
System.out.println(scores);
System.out.println("\n");
System.out.println("\n");
{
System.out.println("Would you like to play again?");
String input = in.nextLine();
if(input.equals("yes")) {
continue Game;
}
}
}
}
To keep it simple, you could just change the exit criteria:
if (!input.equals("yes")) {
break; // end the loop
}
Just a hint: it is considered a good practice to compare a literal against some variable:
if (!"yes".equals(input)) {
break; // end the loop
}
Doing the check this way will not fail with NullPointerException in case input is null, it just returns false in this case.
it's easier if you set the opposite:
if(input.equals("no")) running = false;
That way the while loop gets out cleanly and you don't need to use a cumbersome label to control your flow.
From
Branching Statements
The continue statement skips the current iteration of a for, while , or do-while loop.
You want to jump to the label 'Game' from outside of the labelled while loop,
which is not allowed.