Java method stuck in endless loop while validating input - java

Somehow I am getting some funny play here and I just cant see why.
This method is supposed to make sure that the input is either y or n, and is NOT blank.
I should note this is for school, and the 2 separate error outputs are required.
When I enter a blank line, I get exactly that at the console- a blank line.
After that point, or after a time where I purposely enter bad data, such as x, the very next time I enter a valid data, like y or n, I continue to get the bad data in an endless loop.
What have I done wrong?
public static boolean getContinue(Scanner sc)
{
boolean decision = false;
System.out.println("Continue? Y/N: ");
String userChoice = sc.next();
boolean isValid = false;
while (isValid == false)
{
if (userChoice.equalsIgnoreCase("y"))
{
decision = true;
isValid = true;
}
else if (userChoice.equalsIgnoreCase("n"))
{
decision = false;
isValid = true;
}
else if (userChoice.equals(""))
{
System.out.println("Error! This entry is required. Try again.");
userChoice = sc.next();
}
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
{
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
}
}
return decision;
}
NOTE:
Code was amended to include
New console outputs(Still wrong)
FORMATTED RESULTS
Loan amount: $5.00
Yearly interest rate: 500%
Number of years: 5
Monthly Payment: $2.08
Continue? Y/N:
b
Error! Entry must be 'Y' or 'N'. Try again.
y
Error! Entry must be 'Y' or 'N'. Try again.
y
Enter loan amount:

You don't set the variable userChoice to the new value. Change your last if clause to
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();

Because userChoice never changes inside the loop (which is because you don't change it).

Please look at else if part:
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
here you have done 2 errors:
you have used |, which is bitwise operator, not logical
the logic requires logical AND (&&) to get the cases when the input is not either y or n
SO the correct else-if:
else if (!userChoice.equalsIgnoreCase("y") && (!userChoice.equalsIgnoreCase("n")))
{
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
}

You have to use sc.nextLine() in order to catch the Empty Blank Line. So replace all the instances of sc.next() with sc.nextLine()

Related

JAVA how to write an exception if the user entered a number instead of a string?

Please explain I'm a little confused with do while .
If I enter the name of the city the first time, everything works correctly.But if I enter a number, I get a corresponding message, and when I try to enter the name of the city for the second time, it gives the same message.(about invalid data)
String town=scanner.nextLine();
boolean tryagain = false;
do {
if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format");
scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
}while (tryagain);
I also tried the try and catch option, but I couldn't write an exception if the user entered numbers instead of a string.It doesn't work. Help please.
try {
System.out.println("enter the name of the city");
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format ");
scanner.nextLine();
}
Note the difference between this line of code:
town = scanner.nextLine();
and this line of code:
scanner.nextLine();
They both accept input from the console, but only one of them stores that input in the town variable. To update the town variable with the newly entered value, store that value in that variable:
town = scanner.nextLine();
Try this. Inside if block save scanner.nextLine() to town variable in order to check in the next iteration if it consists only from numbers or it is empty:
Scanner scanner = new Scanner(System.in);
String town=scanner.nextLine();
boolean tryagain;
do {
if (town.matches("[0-9]*")){
System.out.println("You probably entered an invalid data format");
town = scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
} while (tryagain);
put it inside try block and try parsing it as Integer
try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number
}

hasNextInt() keeps waiting for input when pressing Enter

First post/question here and very new to java. Trying to make a small text based movie database app. One part of it is to add a review. The problem is when I just hit [enter] when asked for a Score number [0-10] on the review, the prompt just drops one step down and keeps waiting for input. I want it to be impossible to leave this field blank. Here is what I have so far:
int score;
do {
while (!sc.hasNextInt()) {
sc.next();
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
score = sc.nextInt();
if (!(score >= 0 && score <= 10)) {
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
} while (!(score >= 0 && score <= 10 ));
Scanner is reading tokens, i.e. text separated by whitespaces. That means, that as long as you just press Enter, the next token hasn't even started yet.
One of the fallacies of Scanner is that it's so easy to use, but even easier to misuse, e.g. mishandling user input.
Example: What should happen if used enters 123 abc<enter>? Your code will read 123 and continue, leaving abc in the buffer for the next prompt, which might want text and hence read the abc as that text. Oops!!
Most of the time, to handle bad user input, you should never use hasNextXxx() and nextXxx() methods other than nextLine(). It's the only way to ensure you get one answer (input) for one prompt.
So, you should do something like this:
int score;
for (;;) {
System.out.print("Please enter a number from 0-10: ");
String line = sc.nextLine();
try {
score = Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid input! Not a number.");
continue;
}
if (score < 0 || score > 10) {
System.out.println("Invalid input! Out of range.");
continue;
}
break;
}

Java User Input - Enter integer within certain range or loop back and try again

I have to build a user input template where you can enter a number between 100 and 200. If you type "goodbye", it needs to exit, if you enter a letter, symbol, number outside the range, etc. it needs to prompt you to try again. if you enter a number within the range, it will move on to another question (I haven't included that in the code below).
I got almost everything to work. If you enter a correct number the first time, it works. The "goodbye" and wrong character functions also work. BUT if you enter the wrong character (number or letter) and then, when it prompts you to try again, you put a CORRECT number in the range, it does not accept it and again prompts you to try again.
I need to figure out how to input a wrong character (such as a letter or number outside of range), and then when it prompts you to try again and you put a number between 100-200, it works and exits the loop (which will enable it to go on to the next question/loop).
Here is my code:
Scanner console = new Scanner(System.in);
String Input;
int Number;
boolean isValid = true;
do {
System.out.println("Enter a valid number:");
Input = console.nextLine();
if (Input.equals("goodbye") || Input.equals("GOODBYE")){
System.out.println("You have left");
System.exit(0);
}
char[] numberTester = Input.toCharArray();
for (int i = 0; i<Input.length(); i++){
Character currentChar = new Character (numberTester[i]);
if (!currentChar.isDigit(numberTester[i])){
isValid = false;
System.out.println("Invalid. Try again.");
i = Input.length();
}
if (isValid == true){
Number = Integer.parseInt(Input);
if (Number < 100 || Number > 200){
isValid = false;
System.out.println("Invalid. Try again.");
}
}
}
} while (isValid == false);
}
}
In the beginning your isValid flag is set true. Your do-while loop runs while this flag is false. If you enter something valid in your first round it quits the loop. But if you enter something invalid you set your flag to false and never back again, so it loops forever.
Setting your isValid flag true as first statement in your do while loop should solve your problem.
[...]
do{
isValid = true;
[...]
} while (isValid == false);
It looks like the issue is coming from the fact that once you set the isValid variable to false, it never becomes true, so the do-while loop will loop infinitely.
One way to fix this would be to to set the isValid variable to true at the beginning of each cycle of the do-while loop, so that if nothing triggers it to become false within the loop, the loop will be exited at the end since the condition will not be true.
I think the purpose of this assignment is to learn how to handle exceptions. parseInt will throw a NumberFormatException. Use this to your advantage instead of that toCharArray nonsense.
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
String input;
int number;
boolean isValid;
do {
isValid = true; // reset the validity
System.out.print("Enter a valid number: ");
input = console.nextLine();
if (input.equalsIgnoreCase("goodbye")) {
System.out.println("You have left");
System.exit(0);
}
try {
number = Integer.parseInt(input);
if (number < 100 || number > 200) {
isValid = false;
System.out.println("Invalid. Try again.");
}
} catch (NumberFormatException e) {
isValid = false;
System.out.println("Invalid. Not a number. Try again.");
}
} while (!isValid);
}

IF statement isn't checking variable

Hello I'm trying to write a program that prints 3 numbers from a range being restricted to numbers from 0 to 99,but my If statement isn't double checking the variable.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0);
System.out.println("Outside range program terminated.");
Two problems that I see:
Your second input (within the first IF) is not checked with the code shown.
The else statement will NOT check the above mentioned problem because you've already passed that decision point when the original IF executed. The else is dependent on the IF's result. Here would be one way to fix.
Finally the 'else' needs brackets { }.
int input1 = 0;
Boolean myLoop = true; //Sets up our loop flag
while(myLoop){ //Loop while true
System.out.println("Please enter an integer between 0-99");
input1 = Input.nextInt();
if (input1>99||input1<0){ //If input is outside the range send msg.
System.out.println("Data range error");
}else{ //If input is in range, end loop.
myLoop=false;
}
}
This will continue to check until it get valid values.
While the others have given you a good code sample, I will like to point out where your code issue is. The code is not doing the double checking here because you have placed a semi-colon right at the end of the second if-else check, and the program will do nothing when it fulfill the if condition.I have replaced it with curly bracket. Try to compile and run it again.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0){
System.out.println("Outside range program terminated.");
}

validating if statement not working properly

I'm trying to make an if statement to catch if the user of the program enters a value besides y or n for the question asked at the end of the program "Continue? (y/n): ". But no matter what the value I input "y", "n", or something invalid I get the message "Invalid input try again" from the console. This is only supposed to happen when the choice is not y or n anyone know why it keeps happening regardless of what I input?
import java.util.Scanner;
public class ProductApp
{
public static void main(String[] args)
{
//display a welcome message
System.out.println("Welcome to the Product Selector ");
System.out.println();
// perform 1 or more selections
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("Enter Product Code: ");
String productCode = sc.next(); //read the product code
sc.nextLine() ; //discard any other data entered on the line
//make sure the case the user enters for a product code doesn't matter
productCode = productCode.toLowerCase();
// get the Product object
Product p = ProductDB.getProduct(productCode) ;
// display the output
System.out.println();
if (p != null)
System.out.println(p);
else
System.out.println("No product matches this product code. \n");
System.out.println("Product count: " + Product.getCount() + "\n" );
// see if the user wants to continue
System.out.println("Continue? (y/n): ");
choice = sc.nextLine() ;
System.out.println();
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
{
System.out.println("Invalid input try again");
continue;
}
}
}
}
also wherever I get the message "Invalid input try again" the program asks for a new input once but then moves on whether it's valid or not. it runs again if its "y" and closing if its anything else instead of asking a second time for a valid input.
Your condition is not working because you have ; after your if statement.
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
^^
Change
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
{
System.out.println("Invalid input try again");
continue;
}
TO
if(!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")))
{
System.out.println("Invalid input try again");
continue;
}
your condition is not correct it should be
if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")){
// choice is not y or n
}
choice.equalsIgnoreCase("y") && choice.equalsIgnoreCase("n") it will never be true
because choice may be either y or n but not both
Make it a while statement if you want it to ask until you input y or n. Otherwise it will jump to the big while loop and exit since the big one is asking for
while (choice.equalsIgnoreCase("y"))
so, the inner loop would look like this:
while( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") )
{
System.out.println("Invalid input try again");
//continue; //not needed
}
EDIT: Another approach would be to treat only 'y' as yes and everything else as 'n'
// pseudocode
while (!choice.equalsIgnoreCase("n")) {
// do your thing
if (!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n"))) {
choice = "n"; // so exit
}
}
check your condition. it should be:
if(!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n") ))
{
System.out.println("Invalid input try again");
continue;
}
if( !(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) )
{
System.out.println("Invalid input try again");
continue;
}
Try this .
I think you should change if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")); to if(!choice.equalsIgnoreCase("y") || !choice.equalsIgnoreCase("n")){. Cause using && checks for both condition to be true and this can never happen since choice can contain only one value.

Categories

Resources