Don't continue if first statement is = 0 - java

So I have this piece of code and I only want option 2 to be executed if option 1 has a value other than 0. If it has 0, throw an error. Any help is appreciated. Thanks! :)
if (option == 1){
System.out.println("YOU HAVE SELECTED OPTION 1");
System.out.println(accounts[i].getOwner().getfirstName() + " " + accounts[i].getOwner().getlastName() + ", Please enter your yearly salary:");
accounts[i].setyearlySalary(in.nextDouble());
}
else if (option == 2){
System.out.println("YOU HAVE SELECTED OPTION 2");
System.out.println(accounts[i].getOwner().getfirstName() + " " + accounts[i].getOwner().getlastName() + ", Please enter any additional salary:");
accounts[i].setotherSalary(in.nextDouble());
}

I would reccomend you to create a function to set additional salary and call it for option 2 code and for case if option 1 == 0.

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.

printing out a line twice after keyPressed

I have created a monopoly game, and the problem right now is that once I press "y" to buy a property, it prints out the previous lines again, rather than going straight through the loop.
if (board1[pos_l].getType().equals ("prop")) {
if (board1[pos_l].getAvail() == (true) && numClicks!=0) {
println (board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + ". Press y to buy.");
println("player 2 roll the die (a) if player 1 doesn't buy it");
println("");
if (key == 'y' ){
board1 [pos_l].setAvail(false);
board1[pos_l].setOwner (name1);
p1money = p1money - board1[pos_l].getPrice();
println("you have bought it! you now have " +p1money + ". player 2 press 'a' to roll the die.");
numClicks=0;
}
}
I expect the output to be "you have bought it! you now have $___ .....". Instead, it's printing out "board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + Press y to buy. player 2 roll the die (a) if player 1 doesn't buy it" again after I press y.
You're not telling it not to print out the lines when the user presses Y. You need to move those lines to an else block:
if (board1[pos_l].getAvail() == (true) && numClicks!=0) {
if (key == 'y' ){
board1 [pos_l].setAvail(false);
board1[pos_l].setOwner (name1);
p1money = p1money - board1[pos_l].getPrice();
println("you have bought it! you now have " +p1money + ". player 2 press 'a' to roll the die.");
numClicks=0;
} else {
println (board1[pos_l].getName() + " is available for $" + board1[pos_l].getPrice() + ". Press y to buy.");
println("player 2 roll the die (a) if player 1 doesn't buy it");
println("");
}
}

Using a loop to figure out the number of tries left

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.

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