Why are my while loops not working and ignoring code? - java

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.

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.

Wondering what is wrong with my code; it gets hung up on the while if loop

I've looked around and can't seem to find an answer as to what exactly the problem is. It executes fine up until the loop and then it seems to ignore the loop and gets hung up so I am rather confused.
package classGame;
import java.util.*;
public class GameTwo {
static int randomNumber;
static int numOfGuess = 5;
static Scanner GameTwo = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Frank: Hello there! My name is Frank. This is the introduction to the game.");
System.out.print("Frank: Please tell me what you would like to be called: ");
if(GameTwo.hasNextLine()) {
String userName =GameTwo.nextLine();
System.out.println(userName + ": My name is: " + userName);
System.out.println("Frank: Well " + userName + ", it's nice to meet you. ");
System.out.println("Frank: Lets play a little game, I want you to guess a number, It's already" +
" in my head and it's between 1-10.");
int guessResult = 1;
int randomGuess = 0;
while(guessResult != -1) {
randomGuess = GameTwo.nextInt();
guessResult = checkGuess(randomGuess);
}
while (randomGuess != guessResult) {
System.out.println(userName + ":Is the number: ");
randomGuess = GameTwo.nextInt();
if(randomGuess < 1 || randomGuess > 10 || randomGuess > guessResult || randomGuess < guessResult) {
System.out.println("Frank: Thats not right "+ userName);
} else if (randomGuess == guessResult) {
System.out.println("Frank: Hey...Thats pretty good...You got it!");
}
}
}
}
public static int getRandomNum () {
randomNumber = (int) (Math.random()*10);
return randomNumber;
}
public static int checkGuess(int guess) {
if(guess == randomNumber) {
return -1;
} else {
return guess;
}
}
}
here is what it prints out up to the loop
Frank: Hello there! My name is Frank. This is the introduction to the game.
Frank: Please tell me what you would like to be called: T
T: My name is: T
Frank: Well T, it's nice to meet you.
Frank: Lets play a little game, I want you to guess a number, It's already in my head and it's between 1-10.
I think this is an issue with how Scanner.nextInt() works. nextInt() takes in the next Integer found but it does not clear the buffer like nextLine() does.
See this link for more info about this issue: How does input.nextInt() work exactly?
Try this and see if your loop continues properly:
while(guessResult != -1) {
randomGuess = GameTwo.nextInt();
guessResult = checkGuess(randomGuess);
GameTwo.nextLine();
System.out.println("Random Guess: " + randomGuess); //Try here
}
I think the reason the loop is getting hung up is because nextInt() keeps finding the randomGuess number still in the input buffer and executing over and over again. To test that, simply put System.out.println("Random Guess: " + randomGuess); in the loop and see if it is printing with the same number over and over again.
Otherwise, I would need to see the output of your program to further diagnose the issue.
Edit: Can you post the input/output of your program up to the point it crashes? This will help. Also, did you have the System.out.println() in your loop beginning with while(guessResult != -1) or the second one?
Edit 2: I tested this code with my edits and it seems to work as intended (ish). The initial while loop does not do what is intended. The "game" aspect of guessing the correct number all happens in the first loop. I am "playing" the game and guess numbers but once I get it correct, it moves to the second loop, presumably where you actually wanted to "play". The correct number is gotten in the first loop and then the guessResult variable gets set to -1. Then when the user tries to guess where they are supposed to, the "correct" number is now -1.
I don't think the game was ever "hung up", it was just silently waiting for your input in the first loop. To solve this:
Simply remove the first while loop (and its contents) and the game works as intended.

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;
}
}

String concatenation in relation to JOptionPane

So, I haven't done any programming in a few months because I'm taking general prerequisite courses right now and I have a job, so now I'm a little rusty and I'd like to be up to par for when I take my next programming class in the Fall. Long story short, I'm trying to get back on track, so I'm making a silly practice program.
I made this program with all input and output done through the console using a Scanner, but then decided to go ahead and move over to JOptionPane as an interface. It was a pretty easy transition overall, but I'm just having a problem with the output at the very end. I'm trying to make all of the elements of an array into a nice, grammatically correct String for easy output in JOptionPane, but I can't really get my concatenation to work correctly. I realize that the output is not grammatically accurate when the amount of cats is one or two. I'll work on that after this, it's an easy fix.
Here is the code:
import javax.swing.JOptionPane;
public class JavaTestClass {
public static void main(String[] args)
{
//Get number of cats
int numOfCats = Integer.parseInt(JOptionPane.showInputDialog("How many cats do you have?"));
JOptionPane.showMessageDialog(null, "Oh, so you have " + numOfCats + " cats.\n", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
//Get cat's names
String[] catNames = new String[numOfCats];
for(int i=0;i<numOfCats;i++)
{
catNames[i] = JOptionPane.showInputDialog("Enter the name of cat " + (i+1) + ": ");
}
//Output cat's names
String catNameList = null;
for(int i=0;i<numOfCats;i++)
{
if((i+1) == (numOfCats-1))
{
catNameList.concat(catNames[i] + ", and ");
}
else if ((i+1) == numOfCats)
{
catNameList.concat(catNames[i] + ".");
}
else
{
catNameList.concat(catNames[i] + ", ");
}
}
JOptionPane.showMessageDialog(null, "So your cat's names are: " + catNameList, "Names of cats", JOptionPane.INFORMATION_MESSAGE);
}
}
Sorry about the spacing. It didn't really come out the way I wanted it to on here, but I don't have all day the indent all of the lines just for the sake of the post. Anyway, it should be relatively obvious, even without my long description above what I'm trying to do. Any help would be much appreciated. Thanks in advance.
Strings are immutable. Every operation that modifies a String returns a new one.
So it should be:
catNameList = catNameList.concat(catNames[i] + ", and ");
Also don't initialize it to null.
String catNameList = "";
Reference the String concat javadoc. Concat method is returning the result of concatenation.

Java: Code ain't working the right way

First you have to know that I'm a noob to Java, i just started to code and it's my first programming language. So please don't be angry if I'm begin a bit stupid, I just wanna learn to code - Thanks
I'm trying to make a simple " guessing game ", but my code aren't waiting for the user-input.
please help me, I don't know what to do.
My code:
public static void main(String[] args)
{
//Creating the scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Creating the two random numbers.
Random rand = new Random();
int userNumber = rand.nextInt(10) + 1;
int comNumber = rand.nextInt(10) + 1;
//Asks the user what to do.
System.out.println("Your number is: " + userNumber +" of 10");
System.out.println("Do you think that your number is Heigher(H), Lower(L) or Equal To(E) the computers number");
//Checking if the user is right.
//If the user types in LOWER
if(userNumber < comNumber && input.equals("L"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber < comNumber && !input.equals("L"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in EQUAL TO.
if(userNumber == comNumber && input.equals("E"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber == comNumber && !input.equals("E"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
//If the user types in HEIGHER.
if(userNumber > comNumber && input.equals("H"))
System.out.println("You are right. The computer's number is: " + comNumber);
if(userNumber > comNumber && !input.equals("H"))
System.out.println("You are wrong. The computer's number is: " + comNumber);
else
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
}
I would be happy if you could help me out whit my problem, and tell me how I can remove the #SuppressWarnings("resource") / explain why it have to be there.
You're using Scanner wrong. You need to call scanner.nextLine() to get input (a String) from the user, and you need to convert the String to an integer (with Integer.parseInt) to compare it with other ints.
You're going to have to import java.util.Scanner into your project. Take a look at this link that will give you plenty of information about it.
Edit: Just noticed you had it at the top. The next thing you should do is create a variable, say "guess" of type string, and you want to assign input.next() to that variable. Then you can replace the input.equals() functions with the guess.equals() function.
http://www.homeandlearn.co.uk/java/user_input.html
You should import java.util.*;
And You aren't taking any input from user, try
int inp=input.nextInt();
To answer your original question, you are getting an error because you aren't importing java.util.Scanner
import java.util.Scanner;
To address some of the other issues:
You are not reading in anything from the user. You use the Scanner methods to do this.
String guess = input.nextLine() is what I would use.
Secondly, your if statements would not work the way you are using them. This may not be the most compact but it is good for readability.
if(guess.equals("L")){
if(userNumber < comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("E")){
if(userNumber == comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else if(guess.equals("H")){
if(userNumber > comNumber){
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
I also suggest closing the Scanner as good practice at the end. input.close()
You might want to read the documentation of the Scanner class. It has some examples on how to use it properly.
The main problem is in your if statements: With input.equals("L") you are asking if the scanner object is equal to the string "L", which is impossible, since they aren't the same type.
To get a string from the input stream you could use input.next() and compare that to "L". Remember though to only call it once before all the ifs, otherwise the programm waits for a new input at every condition check.
Regarding the warning:
As you can read in the documentation, Scanner needs to be closed with input.close() after use.
And just as a hint, never use the #SuppressWarnings annotation if you don't know what your are suppressing. It is meant as a tool for you to use when you know that something the compiler warns you about cannot happen.
In this case it tried to warn you about a resource leak, which is absolutely correct.
EDIT:
Just as an idea how you could improve your design. You could do something similar to:
String expectedInput;
if (userNumber < comNumber) {
expectedInput = "L";
} else if (userNumber == comNumber) {
expectedInput = "E";
} else {
expectedInput = "H";
}
String userInput = input.next();
if (userInput.equals(expectedInput)) {
System.out.println("You are right. The computer's number is: " + comNumber);
} else {
System.out.println("You are wrong. The computer's number is: " + comNumber);
}
You would still have to check for wrong input though.
This has a more natural flow to the logic and is easier to read.
Another advantage would be that you are separating two different concepts: finding out who had the higher number and finding out if the user guessed right. This might seem like a little thing now, but things like the seperation of concepts and levels of abstraction will become more important the more complex your software gets.
Just had another idea. You could even get rid of the code duplication in the last bit and add a check for wrong input like this:
String userInput = input.next();
boolean isInputValid = Arrays.asList("L", "E", "H").contains(userInput);
if (isInputValid) {
String rightWrong = userInput.equals(expectedInput) ? "right" : "wrong";
System.out.println("You are " + rightWrong + ". The computer's number is: " + comNumber);
} else {
System.out.println("You can only type in ' L ', ' E ' or ' H '.");
}
Though it is debatable if using a ternary operator is good style...

Categories