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();
}
Related
I'm currently learning how to code and I'm facing a bit of a problem, and I was hoping someone could help me out. Currently, Im creating a program that prompts for military status and shows appropriate discounts, but I would like it to loop if the answer isn't one of the given options.
This is my code:
public static void main(String[] args)
{
char milID = ' ';
char status = ' ';
String validMilitaryID = JOptionPane.showInputDialog("Do you have a valid military ID?");
milID = validMilitaryID.charAt(0);
Scanner valid = new Scanner(System.in);
if (milID == 'Y') {
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
} else if (milID == 'y'){
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
}else{
JOptionPane.showMessageDialog(null, "Sorry, you are currently ineligible for a Military Discount");
System.exit(0);
}
if (status == 'A'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 15% discount!");
} else if (status == 'R'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 13% discount!");
}else if ( status == 'D'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 10% discount!");
} else {
JOptionPane.showMessageDialog(null, "Sorry! That was not a valid answer.");
}
System.exit(0);
}//END MAIN
If anyone is able to help, can you explain the process as well. Since I am new to Java I would like to learn rather than just have a fix.
Thank you!!
1) you may call your input as well as your if code into a while loop
2) maybe use a switch instead of if..else if
something from the logic such as:
boolean checkInput = true;
while (checkInput) {
// now get your input... not coded
switch (milId) {
case "y","Y": bla bla, break;
case "x","X": bla bla, break;
otherwise: bla bla, break;
}}
3) use a variable for your account value; you could code this with a lookup
An integral part of Java (or programming in general) is missing from your code, and that is the "while loop". I do not know how much knowledge of Java you have so far, but a while loop repeats what's in its block of code until a requirement is met. If you are adding a feature that repeats the survey if the wrong input is given, a while loop at the beginning of your conditionals is what you need.
Pseudocode
create variable called correctAnswer
Do you have a military id? Enter y or Y if yes, any other key for no
if yes, correctAnswer = 1
if no, correctAnswer = 0 and while loop is skipped
while correctAnswer = 1
{
Are you active, retired, etc?
If yes, what is your status?
if A, R, or D is given, display congrats message. correctAnswer = 0 //end
if anything other than A, R or D is given, then correctAnswer = 1 //repeat
}
The while loop in the second block of conditionals keeps repeating the loop until a correct answer is given.
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.
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.
Ok, so my computer teacher has asked us to make a simple game that asks the user to guess a radomly generated number, but I want to take it one step further and make it so that it display error messages when the user tries certain things. The problem here is that I am new to booleans and well, I am having a bit of trouble using java.util.Scanner and booleans. So, if anyone could take a quick look at this I would appreciate it.
import java.util.Scanner;
import java.util.Random;
public class MoreGuessing{
//Instantiation
Scanner reader = new Scanner(System.in);
Random number = new Random();
//Variables
int randomnumber = number.nextInt(10) + 1;
int cntr = 1;
static String decimalguessed;
String error1 = "Error001: Decimal found, please enter a whole number between 1-10." + "\n" + "Program terminated......";//Decimal portion error.
String error2 = "Please enter a positive number." + "\n" + "Program terminated......"; //Negative number error.
String error3 = "Unknown character entered." + "\n" + "Program terminated......"; //Unknown character error.
//Verifier
public static boolean verifyLetters() {
if (decimalguessed.matches("[a-zA-Z]+")){
return true;
}else{
return false;
}
}
public static void main(String [] args){
//Input and display
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextLine();
//Process and Errors
while (decimalguessed != randomnumber) {
if (verifyLetters() != false){
System.out.println(error3);
System.exit(1);}
if (decimalguessed % 1 != 0) {
System.out.println(error1);
System.exit(1);}
if (decimalguessed < 0) {
System.out.println(error2);
System.exit(1);}
if (randomnumber != decimalguessed){
System.out.println("You've lost, please make another attempt.");}
System.out.print("Please enter a whole number between 1-10: ");
decimalguessed = reader.nextDouble();
cntr++;
}
if (cntr == 1) {System.out.println("Congratulations! You've guessed the number on your first attempt!");;
}
else {System.out.println("Congratulations! You've guessed the number, it took you " + cntr + " tries");}
}
}
You need to parse your input. decimalguessed is a string, and so you can't do comparisons like decimalguessed % 1.
You can convert it to an integer like this:
int guess = 0;
try {
guess = Integer.parseInt(decimalguessed);
} catch (NumberFormatException e) {
System.out.println("Your guess was not an integer: " + e.getMessage());
System.exit(1);
}
This will handle both cases where decimalguessed contains letters, and where it contains decimal points/fractions. decimalguessed is still a string, but guess now contains the integer version of it, so you can compare it to randomnumber properly. (Your loop would have never exited before, because a string is never == an integer)
Some other notes:
You should never have:
if (condition) {
return true;
} else {
return false;
}
This can always be simply replaced with
return condition;
It feels like you're very new to this. Welcome to programming!
So first, in Java generally you're not going to have all of that instantiation and variables stuff outside of your main function, unless you're going to make everything static. I would move all of that into your main function, un-static the decimalguessed variable and setup your verifyLetters function to take an argument of String decimalguessed. It may also be wise to check if the value is a number, rather than seeing if it is not a letter. There a lot of non-number, non-letter characters.
Once you've figured out that the guess is a number, you need to tell java it is one (cast it) to a decimal, then do you further comparisons against that decimal.
Darth Android also makes some good points, especially about booleans. You should never have the only result of an if/else be to return a boolean, just return the boolean. Also avoid comparisons to true/false, just do the if on the function/variable alone, or negate it with an '!' to check for false.
Good luck!
I am trying to use the while loop for re-running parts of code in my simple program. In this program, the user makes a simple account, types in a verification number, then signs in. Once signed in, I wish to allow the user to sign out, edit his profile settings and more. However I have a small problem.
Say the user has just edited their account settings. Instead of the program terminating, I want them to be able to return to the "menu".
The problem lies with how to do that. As there is no goto statement in java, from what I have read, I must use the while loop. I have no idea of how to go about that. I just can't wrap my head around it. Loops have always confused me. Also, should I even use the while loop? Would it be better to use the for or do-while loops? And what expression should I use? Will I need the break statement?
I know it isn't a concrete question, but any help that puts me on the right path is well appreciated.
Below is the full code for reference.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println("To confirm you are not a robot, please enter this code: " + randm);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You have placed a comment //where would I go if the user signed out?
The answer is, You will show the message to sign in when he is signed out, so that he can sign in again. You can do this by using for loop or loop or whatever loop you want. That means the part of user login will be in a loop, if the user logged in then the menu will be shown up. If the user sign out, the sign in form will be shown up infinitely.
You can put your code inside do. It will not break and will keep looping.
do{
}
while(true);