User input if statements skipping - java

So what I am trying to accomplish is having the user be able to order a item, so far just potatoes, and then to confirm the order using a "yes" or "no" input. What is happening however is the secondary input if statements are bing skipped over and the rest of the code runs. Can anyone tell why these if statements are not being implemented properly?
if(next.contains("potatoes")); {
// Add in the quantity function later;
System.out.println("\nAre you sure you want to add potatoes?");
}
if(next.contains("yes")); {
System.out.println("\nYour basket:" + itemOne +" " + potatoCost);
}
if(next.contains("no")); {
System.out.println("You have not added " +itemOne + " to your cart.");
}
}
while ( next.equalsIgnoreCase("exit") == false );
System.out.println("You have decided to stop shopping!");
System.exit(0);
}
}

Related

Setting up while and do-while loops from user input questions

I have to create a code used to determine the amount of insurance payout. I have to use a while loop after the initial prompt asking if they want to get an analysis. Then I need to use nested do-whiles, 2 do-while loops, in the prompts and if-else-ifs. I need help with the loops.
`
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String answer = " ";
String cont = ("%nMUTUALLY ACCIDENTAL, INC." +
"%n%nDo you want an analysis of earthquake coverage" +
"for your property? Enter 'Y' or 'N': ");
System.out.printf (cont);
(Scanner (answer = input.nextLine ()));
while (answer.equalsIgnoreCase ("Y"))
System.out.printf ("%nMUTUALLY ACCIDENTAL, INC." +
"%n%nEarthquake coverage analyzer" +
"%nPlease enter your name: ");
do
System.out.printf("%nPlease enter the insured value of your home: ");
System.out.printf("%nRichter Scale Damage Assessment"+
" 9.0+ Total destruction."+
" 8.0 Most structures dell."+
" 7.0 Many buildings destroyed"+
" 6.0 Many buildings considerably damaged, some collapsed."+
" 4.5 Damage to poorly constructed buildings."+
" 3.5 Felt by many people, no destruction."+
" 0 Generally not felt by people."+
"%n%nPlease enter the Richter scale value for the earthquake: ");
do
system.out.printf("%n“Your Name: “,Xxxxxxxxxx Xxxxxxxxxxxxxxx
“Home’s Insured Vale: “,$ZZZ,ZZZ,ZZZ9.99
“Richter Scale: “,Z9.99 or -Z9.99
“Is this information correct? ‘Y’ or ‘N’: “);
System.out.printf("%nDo you have another property? Enter 'Y' or 'N': ");
coverage = String.format(%n%nPAYOUT FOR EARTHQUAKE "+
"DAMAGE"+
"%N%NHOMEOWNER: %S"+
"$n$nDATE: %tD"+
"%nTime: %tr%n, insured, dateTime, dateTime);
coverage +=String.format("%n%-52s %4s $%,20.2f"+
"%nDeductible $47 $,20,2f"+
"%n46s TOTAL %4s $%,20.2f%n", message, " ", payout, " ", deductible, " ", " ", payout + deductible);
System.out.print(coverage) when richter > 0
exit main()
else
System.out.printf("%nThank you for using the Earthquake" +
"Coverage Analyzer.");
}
}
I can't see a clear question in here so I assume you are stuck on the structure of the loops.
while has the following structure:
// before
while (condition) {
statements;
statements;
}
//after
It first tests the condition. if true, it runs the statements. if the condition is false it skips straight to 'after'
do-while has the following structure:
// before
do {
statements;
statements;
} while (condition);
// after
It first runs the statements. then it tests the condition. if the condition is true it goes back into 'do' and runs the statements again. if the condition is false it goes to after.
You can nest loops like so:
while (someCondition) {
int i = 1;
String s = "";
// other code, just filling this to make it look a bit better
while (otherCondition) {
int j = i + 3; // i is available because this while is inside the block of the other while
}
}
You can do the same with do-while / mix them.
One additional thing: if you use break, you exit the loop you are in. if you have nested loops then you will break from the deepest loop.
while (someCondition) {
while (otherCondition) {
break; // goes to after-inner-while
}
// after-inner-while
}
sometimes you want to jump out of the outer while loop. break can help with this if you use labels. you can name loops like so:
outer: while (someCondition) {
inner: while (otherCondition) {
break outer; // goes to after-outer-while
}
// after-inner-while
}
// after-outer-while
this all also works for for-loops but you specifically asked questions about while loops.
be very careful about not using blocks after your while.
this is allowed but will be hard to read / a source of bugs:
while (someCondition)
doSomething();
it can easily be confuse you into thinking your code works differently than it actually does:
while (someCondition)
doSomething();
doAnotherThing();
the above only runs doSomething inside the loop but someone reading your code will likely think both method calls will be run.
Now to the code you posted:
I think you are expected to do something along the lines of:
boolean answeredYes = false;
while (!answeredYes) {
// ask for user input
// if user input is "Y" set answeredYes to true
}
since you say you need to use a while loop first. I would prefer do-while for this since you can do:
do {
// ask for user input
} while (userinput not what you expect);
My best advice right now is: don't try to write the entire method. Write code for one problem at a time. Start with the Y/N question and what you are supposed to do if the user types Y or N
then move on to the next step and work out what to do and how to do it. Write yourself comments (notes) that let you know what your intentions are.

What alternatives are there for if else statements?

This is a method within my program and I cannot use a bunch of if-else statements for my code. I need alternatives.
public String bedRoom1(){
int newChoice10 = JOptionPane.showConfirmDialog(null,"Would "
+ "you like to explore this room?",
"question",JOptionPane.YES_NO_OPTION);
if (newChoice10 == JOptionPane.YES_OPTION){ //if the user would lieke to
// explore then they are given the option for which objects they woul like to explore
int newChoice4 = JOptionPane.showConfirmDialog(null,"Explore"
+ " the Rocking chair(type YES) or Window(type NO)?"
, "question",JOptionPane.YES_NO_OPTION);
//The following if else statments are still within
//the first statement of the first if statement
if (newChoice4 == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null,"Chair starts "
+ "rocking with no one in it");
}else{
JOptionPane.showMessageDialog(null, "You see a child outs"
+ "ide on a swing and he suddenly vanishes.");
}
}else if (newChoice10 == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null,"You have chosen not "
+ "to explore Bedroom 1 and therefore continue "
+ "into the following room");
}
return null;
}
Can you please provide examples. Thank you in advance.
you can use showOptionDialog with all your choices instead of showConfirmDialog
and use switch - case instead of if then else

Why are my while loops not working and ignoring code?

So, what I am trying to do is get my while loops to do different things based on different key words. What I want is that when I type yes, I want it to exit the program, when I type no, for it to print a new song, and if there is a spelling error, for a message to pop up and allow the user to re enter yes or no to print the same song. I have 4 or 5 songs that I want to print out based on these three commands. In my last while loop. I want it to repeat the song every time the user types continue, and for it to end when the user types yes. I want the same thing to happen where it prompts the user to type again if there is a spelling error. This worked before, and now it does not. When I make a spelling error, it prompts me to enter again but will not print out the song in that loop. It will send me to the last while loop, ignoring all code in between. That last loop will only recognize spelling errors and yes, not continue, even though it did before.
Here is one song loop and my last loop:
import java.io.*;
import java.util.*;
public class FullNurseryRhymes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String aBCs, neverEnds, frogs, frogs2, monkeys, hdd, hdd2;
NurseryRhymes rhymes = new NurseryRhymes();
{
System.out.println("Is the baby asleep? yes\\no");
frogs=input.next();
int byeFrog = 2;
for(int i = 3; i >= 1; i--)
{
if (frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!frogs.equalsIgnoreCase("no"))
{
System.out.println("Non requested input, please retry.");
System.out.println("\nIs the baby asleep? continue\\yes");
frogs = input.next();
if(frogs.equalsIgnoreCase("no"))
{
System.out.print(i + " " + rhymes.getFrogs());
System.out.println(" " + byeFrog + " " + rhymes.getFrogs2());
byeFrog -= 1;
}
else if (frogs.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
}
//last loop
{
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
while(neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
}
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
while(!neverEnds.equalsIgnoreCase("continue")||!neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("Non requested input, please retry");
System.out.println("\nIs the baby asleep? continue\\yes");
neverEnds = input.next();
while (neverEnds.equalsIgnoreCase("continue"))
{
System.out.println(rhymes.getNeverEnds());
System.out.println("Is the baby asleep? continue\\yes");
neverEnds = input.next();
if(neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
if (neverEnds.equalsIgnoreCase("yes"))
{
System.out.println("The baby is asleep");
System.exit(0);
}
}
}
Based on the comments, it sounds like there is too much (potentially) relevant code for us to plough through.
There are three ways you could proceed with this.
You could learn how to use the debugger in your IDE. Use breakpoints and single stepping, and figure out where your mistakes are.
You could comment out parts of the code to track down where the problems are. That may also help you to create an MCVE
You could simplify the code by refactoring common / repetitious code into methods. For instance the "last loop" section is incredibly repetitious.
On the last point, it might actually be less work to throw this code away and start again ... after figuring out what common code can be implemented as methods.
Your question is a bit long. We don't need a story, just an explanation of your problem and a BIT of code, not your whole class. Try putting your while loop on the outside. Have a string outside the while loop called babySleep that starts as "no". Then, while(babySleep.equals("no") execute your code. Then at the end, check if the baby is a sleep, if he is, move on, if not, the while loop will re-execute. Also, instead of .equals try .equalsIgnoreCase so the user can type in "Yes" or "yES" etc.

Labels in Java for exception handling

I'm doing the Java Associate level certification and while we are expressly told we won't be tested on labels, we have been shown them. Looking on here though the advice seems to be never use labels?
I'd like to use them in a catch block/user input console as a means of validating input.
do {//Keep calculator going as long as user wants
numInputCheck:
do {
try {//Force user to input a whole number
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
continue numInputCheck;
}
gradeCalc.isValidMark(mark);//Ensure input is within valid range
}while(!gradeCalc.getIsValidMark());
*etc*......
Is this bad coding?
EDIT: The code above wasn't doing what I thought it was/wanted it to do - it wasn't actually jumping back to the label at all.
I ended up changing the code to
do {//Keep calculator going as long as user wants
do {//Force user to enter number within valid range
do {//Force user to enter a whole number
try {
System.out.print("\nPlease enter the Mark you want to Calculate\n(Enter marks between " + GradeCalculator.getMIN_MARK() + " and " + GradeCalculator.getMAX_MARK() + " only): ");
mark = Integer.parseInt(scn.nextLine());
isValidInput = true;
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid entry - Please ensure entry is a number only.");
isValidInput = false;
}
}while(!isValidInput);
}while(!gradeCalc.isValidMark(mark));
which I'm fairly sure is working correctly.
Anyway, I think I answered my own question - labels are discouraged because people like me try to use them.
No this is not actual example because continue can do all the job by itself without the help of the label .
A good example is when you have 2 nested loops and you want to break the outer loop from a condition in the inner loop
outerloop:while(condition1) {
while(condition2) {
if(condition3)
break outerloop;
}
{
Continue statement skips all sentences above, you have to use break sentence for stopping the loop. Labels are useful for more than one loop, for example:
label1:
for (int i = 0 ; i<10; i++){
for (int j = 0 ; j<10; j++){
if (i+j = 3)
break label1;
}
}

Do while loop error

Hey guys I have here a program wherein a user needs to guess the word which is being asked by the program itself. The codes doesn't have syntax errors, but my problem here is that every time you input the correct word that is being asked for, the JOptionPane (ErrorMessage) still appears.
What I want to happen is that, the user can only have 5 trials, once the user entered a wrong word at the last trial given, it should display the correct word that is asked for. And once the user entered the correct word, it should go to the next word. Please help me fix this I'm stuck in here for like 3 hours already. Thank you very much.
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt) {
int trials = 5;
boolean tryAgain = true;
do{
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
}
else if (!wordLibrary.isCorrect(wordIdx, guessedWord.getText())) {
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
trials--;
guessedWord.setText("");
tryAgain = true;
}
}while(tryAgain && trials > 0);
guessedWord.requestFocusInWindow();
}
//This is the isCorrect method
public boolean isCorrect(int idx, String userGuess) {
return userGuess.equalsIgnoreCase(getWord(idx));
}
This is happening in your action performed. When you loop, you're not giving the user any time to enter new information.
Why do you want to loop here? You don't need it. Just check once. If they're wrong change the components and wait for ActionPerformed to be called again.
If you want to give a maximum number of trials, then you should use some form non-local variable to store it.
When you first give a wrong answer, guessedWord's text becomes the empty String "", so at the next iteration, it will never be equal to the given word, because the String that you get with guessedWord.getText() will now be "".
You need to ask the user for a new word and then get the NEW word!
For example, you could set a private variable int trials in your class, initialized with 5 (in your main method) and another one, boolean tryAgain initialized with true. Then the above method could be written as:
private void guessedWordActionPerformed(java.awt.event.ActionEvent evt){
if (tryAgain && trials > 0) {
if (wordLibrary.isCorrect(wordIdx, guessedWord.getText())){
JOptionPane.showMessageDialog(null, "Your answer is correct! Guess another word.","", JOptionPane.INFORMATION_MESSAGE);
getRootPane().setDefaultButton(nextTrial);
guessedWord.setText("");
wordIdx = (wordIdx + 1) % wordLibrary.getSize();
scrambledWord.setText(wordLibrary.getScrambledWord(wordIdx));
guessedWord.setText("");
getRootPane().setDefaultButton(guessButton);
guessedWord.requestFocusInWindow();
tryAgain = false;
} else {
trials--;
JOptionPane.showMessageDialog(null, "Your answer " + guessedWord.getText() + " is wrong.\n Number of trials remaining: " + trials ,
"Incorrect Answer", JOptionPane.ERROR_MESSAGE);
guessedWord.setText("");
tryAgain = true;
}
} else {
//show "the correct word was..."
}
guessedWord.requestFocusInWindow();
}

Categories