System.exit(0) reached before maximum user attempts made reached - java

I may have confused my self with the logic for some time now and I could use some assistance. So I have created this function to return a Voucher # (size is 4-digits). The pre-condition is two characters entered must be correct and in their respective placing below the application reveals the rest of the Voucher digits (when compared with voucher in record).
I am giving the user 3 attempts to search the voucher with the only two known voucher digits. After three attempts and if the voucher does not exist. I'll lock the user and close the app with System.exit(0).
However, System.exit(0) executes when attempt = 3. It seems I don't have control over my loop.
int attempts = 3;
while (attempts != 0){
if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
VoucherNumber.charAt(1) == VoucherRecord.charAt(1))
System.out.println("Reveal all digits");
}
else if(VoucherNumber.charAt(0) == VoucherRecord.charAt(0) &&
VoucherNumber.charAt(2) == VoucherRecord.charAt(2) ){
System.out.println("Reveal all digits");
}
else{
System.out.println("Reveal all digits");
attempts--;
if (attempts == 0){
System.exit(0);
}
}

You should get new input from user inside the while loop. As it is, you seem to get the input once, then run the loop 3 times with the same input..

Related

java Validations to check if more than one textbox has values

I have three text boxes in my html ,where user can input values. In my java class i am doing validations to check if more than one input box has been entered .If user has entered values in two/three textboxes i need to throw an error message. If he hasnt entered the value in three textboxes also i am planning to throw error messsagae. My code is something like this .
if(!dId.equals("") && !PId.equals("") && !PPup.equals("")){
result.addError(new ErrorBO("only one should only be entered"));
}
if(dId.equals("") && PId.equals("") && PPup.equals("")){
result.addError(new ErrorBO(" one should be entered"));
}
dId,PId,PPup are the variables where i have my values. This code fails for the case where the user enters the value in two text boxes. Is there a simplified way to check all the cases.
int numEntered = 0
if(!dId.equals("")) numEntered ++;
if(!pId.equals("")) numEntered ++;
if(!pPup.equals("")) numEntered ++;
if(numEntered != 1) result.addError(new ErrorBO("Enter values in one text box"));
Basically, increase a counter every time a text box has entry. If anything but 1 of them has text, return your error.

Validating user input in java?

My guessing game takes either 5, 10, or 20 guesses from a user and they are supposed to try to guess a random number chosen by the computer. Everything in my code is working except this: when the code asks the user whether they want 5, 10, or 20 guesses, if the user were to enter 15, for example, which is not one of the options, it goes on and starts asking for their guesses. I need some type of validation that will make sure they enter one of the options. I'm not sure where or how to include this in the correct way since I am new to programming. I've tried several different ways but get errors for all. What I need is if the user puts a number that is not one of the options, it should just ask them again until they input one of the options. Can someone show me how I should do this?
First of all if (answer.length() ==3) makes no sense.
Maybe you meant:
if(answer.equals("yes"))
Besides, to accomplish what you want I would use a Set containing the valid guesses numbers. It is scalable and makes much more sense than checking against multiple values in an if clause. It will look like this:
Set<Integer> validNumberOfGuesses = new HashSet<Integer>(Arrays.asList(5, 10, 20));
int numberOfGuesses = scan.nextInt();
while (!validNumberOfGuesses.contains(numberOfGuesses)) {
/* ask again */
System.out.println(numberOfGuesses + " is not a valid number of guesses, please try again");
numberOfGuesses = scan.nextInt();
}
Take input from the user inside a loop. For example:
System.out.print("How many guesses would you like? (5, 10, 20)");
do {
int numberOfGuesses = scan.nextInt();
//on correct guess, break out of the loop
if(numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20)
break;
System.out.print("Please enter a guess having one of these values (5, 10, 20)");
} while (true);
Unless the user, enters one of the three values, he/she will kept being prompted to enter a correct guess value.
Java has the continue keyword that jumps to start of the current loop when run. See The Continue Statement documentation.
Once you have your user input you can do something like
if (numberOfGuesses != 5 && numberOfGuesses != 10 && numberOfGuesses != 20) {
continue; // jumps to start of while loop block, without running conditional
}
When you receive the "numberOfGuesses" you should check the value of that number before moving on. Otherwise you just move on in your code because you don't actually validate the number.
It may be a good idea to creat a function that returns a boolean value and then you can check the number there.
boolean isValidOption(int number)
In the function you want to perform some comparison and validate. Since you have three options you can opt for something like
if (number == 5 || ... )
You can consider how you'll verify the value as there are many ways. Just compare with valid numbers you know you want, you can do some if statements, or place the numbers in an array and compare the value while iterating through the array, and so on. Hope that helps you get started and happy coding!
Edit: Lastly I should have mentioned, but you need to consider the flow of your code. A loop of somesort like while(!isValidOption()) for your check should be use. Loop around the instructions until the user enters a valid option. You need to consider order of operations here in your code and understand the computer doesn't think for you. It does what you tell it, so understand what you are trying to tell it here. I want to step into my game, if and only if, the condition of isValidOption is met for example.
What you need to do is to stay in the loop until you get input that satisfy your demands for example you can use the following function
private int getNumberOfGuesses(Scanner scan) {
int numberOfGuesses;
boolean numberOfGuesesIsValid;
do {
System.out.println("How many guesses would you like? (5, 10, 20)");
numberOfGuesses = scan.nextInt();
numberOfGuesesIsValid = numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20;
if (!numberOfGuesesIsValid) {
System.out.print("Wrong option !!!");
}
} while (!numberOfGuesesIsValid);
return numberOfGuesses;
}
you can write your code inside a loop to make sure the value is either 5,10 or 20
while(numberOfGuesses!=5||numberOfGuesses!=10||numberOfGuesses=!20);
and the condition if(answer.length()==3 can cause errors. it means it will work every time the input is of length 3,even "noo"

Input Validation regarding integers corresponding to days of the week

I have been reading through Java documentation, but I cannot really seem to find a solution. My program asks for a number of 1-7 corresponding to a day of the week. I want the program to return an error "Sorry, not a valid number" when they enter a wrong number, such as 8,9,20 etc (since they do not correspond to a specific day of the week) My method is not working, any input?
while (!stdln.hasNextInt(1,2,3,4,5,6,7)) {
System.out.println("Sorry, not a valid number.");
stdln.next();
}
I tried
while (dayOfTheWeek > 7) {
System.out.println("Sorry, try again");
stdln.next();
}
But this gets me stuck in a loop
This should do what you want. It will get an int from the user and report when the int out of range. You need to add a terminating condition that will break the loop or it will run until you terminat the application:
while (stdIn.hasNextInt()) {
dayOfTheWeek = stdIn.nextInt();
if (dayOfTheWeek == 0) {
System.out.println("Zero was entered. Exiting");
break;
}
if (dayOfTheWeek < 1 || dayOfTheWeek > 7) {
System.out.println("Sorry, not a valid number.");
}
// do something else with dayOfTheWeek
}
This method call in your code is invalid. This method doesn't take 7 integers as arguments :
stdln.hasNextInt(1,2,3,4,5,6,7)
Also keep in mind that next() method will get every char you input including new lines. You will also have to assign the result of next to a variable for it to be any use.

Stuck in a while loop only sometimes

I am having a heck of a time trying to figure out why I can't leave a loop. What I need to do is leave the loop if my Boolean, forward, is set to true. (The Boolean has been set to false above the while loop.
When I run the code snippet below I and enter a positive number I can only enter an unlimited amount a numbers. When I enter a negative number I get one prompt telling me that's not allowed and to try again. After than I am stuck in the similar situation above. It doesn't matter what I enter next it will just keep letting input over and over again.
{
while (forward == false)
if (n2 == 0)
{
System.out.println("Sorry, the 0 is not a valid entry for the second number, try again!");
n2 = in.nextInt();
}
else
{
forward = true;
}
}
You can get away with using no extra variables
n2 = in.nextInt();
while (input == 0){
System.out.println("Sorry, 0 is not valid input");
n2 = in.nextInt();
}
as the forward is a boolean, you can use it directly instead of compare
forward == false.
If you wanna use this variable (I will not go thru the path of the best way achieve your aim), you can do the follow:
while (!forward) {
if (n2 == 0) {
System.out.println("Sorry, the 0 is not a valid entry for the second number, try again!");
n2 = in.nextInt();
} else {
forward = true;
}
}
Do you have an outer while loop that makes you go back into your while loop? An efficient way to solve loop issues is to debug the code a line at a time.
If you are in Eclipse, set a breakpoint (a place where your program will pause) by clicking on the line number just before entering the while loop. Then run the program, and you will see the current line highlighted. Then move line by line by pressing F6 repeatedly. In the bottom pane you can also find the current values of variables.
Now if you inspect your code line by line you will have a better idea of what's going on.

WHILE repeats before ELSE is evaluated

I've nested an IF ELSE statement inside a WHILE statement, but am confused as to why the WHILE is interpreted before the ELSE (when the IF fails). A user is asked to enter a number from 1-10 (inclusive). If the number is inside that range, the program ends. If it's outside of that range, I want to display an error and then prompt them to again enter a number.
It works well if I put the "prompt" before the WHILE, but then I have to put it again inside the ELSE statement for it to show up again. I found this question, but it didn't appear to answer the issue I'm running into. I'm admittedly a Java novice, so I apologize if I'm missing some fundamental aspect of Java.
import java.util.Scanner;
public class Rangecheck {
private static int userNumber; //Number input by user
private static boolean numberOK = false; //Final check if number is valid
//String that will be reused in the DO statement
private static String enterNumber = "Please enter a number from 1 to 10: ";
public static void main(String[] args) {
//Print string
while(!numberOK) // Repeat until the number is OK
{ System.out.println(enterNumber);
Scanner input_UserNumber = new Scanner(System.in); //input integer
userNumber = input_UserNumber.nextInt();
if (10>= userNumber && userNumber >= 1) //Check if 10>=input>=1
{
/*
** If number was valid, congratulate the user and mark numberOK true
*/
System.out.println("Good job! The number you entered is "+userNumber+".");
numberOK = true; // Congratulate user / exit loop if successful
}
else ; //if (10 < userNumber && userNumber < 1)
{
System.err.println("The number entered was not between 1 and 10!");
System.err.print(enterNumber); // Error; user retries until successful
}
}
}
}
I'd expect the System.err.println() to be evaluated in the else statement and then the whileto be evaluated, so that this gets returned:
The number entered was not between 1 and 10!
Please enter a number between 1 and 10:
I've sort of worked around this by putting enterNumber just before while, then putting a second
println in the else statement immediately following the error. It returns what I expect, but I believe I'm fundamentally misunderstanding something.
Let's suppose you have the following code:
while (whileCondition) {
//Inside while, before if
if (ifCondition) {
//Inside if
} else {
//Inside else
}
}
This cycle will execute repeatedly, until the whileCondition becomes false. Whenever the ifCondition is true, the operations inside if will be executed, otherwise the operations inside else will be executed.
Back to your problem:
Your line of
System.out.println(enterNumber);
is at the start of the while. So before the code even gets to your if, the content of enterNumber is displayed on the console. Later, your if is evaluated and if you enter, let's say 22, the condition given to the if will be false and the content of the else block will be evaluated.
The else statement is repeated before the while statement. There can however sometimes be a problem with Streams. A Stream does not necessarily print the data immediately. Especially in the case one uses two different streams, the order of printing the output data can be interleaved.
You can use:
System.err.flush();
to ensure the data is written to the console first.
Add this statement in else body:
numberOk=false;

Categories

Resources