how to avoid pressing several time enter affects the input data? - java

I'm writting a JAVA Class to validate input data, especifically integer numbers.
The class I develop is running fine but when I press more than one time enter and then a char type, it display several times " Error!! Invalid number. Try again. " and I would like to avoid it.
I have use nextLine() method but it doesn't seems to correct it.
Here is the Class:
package chapter07.libro;
import java.util.Scanner;
public class Validator_integer
{
public static int getInt (Scanner scanner, String promt)
{
int numberInteger = 0;
boolean isValid = false;
System.out.println(promt);
while(isValid == false)
{
if(scanner.hasNextInt())
{
numberInteger= scanner.nextInt();
isValid = true;
}//if
else
{
System.out.println("Error!! Invalid number. Try again.");
}//else
scanner.nextLine();
}//while
return numberInteger;
}//getInt
}//Validator_integer
and next is the app to use the class:
package chapter.prueba;
import java.util.Scanner;
import chapter07.libro.Validator_integer;
public class Test_Validator_Integer
{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
int number = Validator_integer.getInt(sc, "Enter integer number: ");
System.out.println(number);
System.out.println("Continue (y/n): ");
choice = sc.next();
}//while
}//main
}//Test_Validator_Integer
The results I get are next:
Enter integer number:
2
2
Continue (y/n):
y
Enter integer number:
(Here I press several time enter)
xx
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
Error!! Invalid number. Try again.
2
2
Continue (y/n):
n
So the part of (Error!! Invalid number. Try again.) displayed several times, is the one I would like to avoid.
Does any one know how to fix it???
Thanks in advance!!!

Before you read from System.in, make sure to "clear" it's contents to get rid of buffered/queued-up input. If there are n characters queued-up, then skip that many chars and you'll need to enter something new.
int n = System.in.available();
System.in.skip(n);
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

Related

Java. Scanner Trying to to a loop until user quits

I've been trying to make a while loop where I enter in a movie number until the user types 'q' for quit, but every time I enter a valid number, I have to enter it twice before it prompts me with the "Enter movie number" message again. And the break function doesn't work when I wish to leave the loop. I simply wish to enter in the movie number once and break out when I want to.
public class Main {
public static void main(String[] args) {
while(true)
{
System.out.println("Enter in movie number: ");
Scanner input = new Scanner(System.in);
if(!input.hasNextInt())
{
System.out.println("invalid input");
continue;
}
if (Integer.parseInt(input.next()) < 0)
{
System.out.println("invalid no negative numbers");
continue;
}
if(Objects.equals(input.next(), "q"))
break;
}
}
I tried other variations of the while loop, but a similar thing has happened.
I assume your intention is to get one line of input, and if it is a number, process it somehow, and if not check if the user wants to quit.
You've got a couple problems with your program, firstly, you're creating a new Scanner within the while loop, which creates unnecessary overhead. Second, you're trying to get 2 lines of input within your loop, you wait for the user to input an integer, then you try to parse that integer with input.next(). Afterwards, you call input.next() again to check if the user wants to quit. By calling next() twice, you're requiring the user to input 2 lines, causing the issue you were describing.
You can fix this by calling next() once and storing its return value in a variable, then check if it equals q for quit, otherwise you can parse an integer value from it.
Here is working code that applies fixes to these issues:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter in a movie number:");
// Get user input
String input = scanner.next();
// If the input equals q, we break out of the loop
if(input.equalsIgnoreCase("q")) break;
int intInput;
try {
// Get integer input
intInput = Integer.parseInt(input);
} catch(NumberFormatException e) { // Input was not a number
System.out.println("Invalid, must input a number");
continue;
}
if(intInput < 0) {
System.out.println("Invalid, no negative numbers");
continue;
}
}
}
}
Also, a small note, instead of using Object.equals to check if two strings are equal you can just use the equals method inside of the String class like so: str1.equals(str2).

How to have check user input using scanner without having scanner prompt multiple times

So im writing a couple methods that require the user to input what hour(1-24) they want. I need however to check whether they enter in an int, and a number between 1-24. The problem is that the scanners are called multiple times if sent to the error statement. I don't know how to do this without having these issues.
public static int getHour(Scanner scan){
int hour=0;
System.out.println("Enter the hour for the showtime (1-24):");
do{
if((!scan.hasNextInt())||((hour=scan.nextInt())<1)||(hour>24)){
System.out.println("Enter a valid number");
scan.next();
} else{
return hour;
}
}while((!scan.hasNextInt())||(hour<1)||(hour>24));
return hour;
}
Ideally it only prompts one time when entering in a not valid input such as a string or int outside of 1-24. but it prompts twice or sometimes once depending on the order of what incorrect input you put in.
Any help would be appreciated, thanks
You're encountering this problem because .hasNextInt() does not advance past the input, and .nextInt() only advances if translation is successful. A combination of loops and if-statements can thus cause confusion as to whether or not the scanner will advance. Here's your method rewritten to have the scanner prompt only once for each bad input:
public int getHour(Scanner scan) {
System.out.printf("%nEnter the hour for the showtime (1-24): ");
while (true) {
input = scan.next();
entry = -1;
try {
entry = (int)Double.parseDouble(input);
} catch (NumberFormatException e) {
// Ensures error is printed for all bad inputs
}
if (entry >= 1 && entry <= 24) {
return entry;
}
System.out.printf("%nEnter a valid number: ");
}
}
I prefer to use an infinite loop in this case, but as that can be dangerous, receive it with caution. Hope this helps!

How to prevent user from entering white space or just hitting enter when a number is expected?

I'm trying to only accept numbers from a user. This code works for giving them an error message if they enter a letter. But it doesn't work for if they hit Enter or just white space. I've tried initializing a String called test as null and then setting scnr.nextLine() = test, and then checking if test is empty, but I didn't understand how to keep the rest of the program operating correctly when I did that. Scanner is very tricky to me. Please help!
double mainNumber = 0;
System.out.print("Enter a number: ");
if (scnr.hasNextDouble() ){
mainNumber = scnr.nextDouble();
System.out.println(mainNumber);
scnr.nextLine();
}
else {
System.out.println("Sorry, please enter a number.\n");
scnr.nextLine();
}
You have to use while-cycle and loop input as long as needed before user put a valid number.
This code
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double mainNumber = 0;
boolean isValidNumber = false;
System.out.print("Enter a number: ");
while (isValidNumber == false) {
String line = scnr.nextLine();
try {
mainNumber = Double.valueOf(line);
isValidNumber = true;
} catch (NumberFormatException e){
System.out.print("Sorry, please enter a number.\n");
}
}
System.out.println("Main number is: " + mainNumber);
}
Having this sample output :
Enter a number: sdfgsgxb
Sorry, please enter a number.
xcvbxcvb
Sorry, please enter a number.
gsfdfgsdf
Sorry, please enter a number.
aearg
Sorry, please enter a number.
15.77
Main number is: 15.77
Well I guess your code is in a while loop or something ? So that it keep asking until the user enter the right value.
Then you should (for convenience) use String str = scnr.nextString() instead of nextDouble() and analyze the string it returned.
You can use str.trim() to remove whitespaces (and then check if string is empty with str.isEmpty() ), and to check if it's a number you can use regexp ( How to check that a string is parseable to a double? and any regex tutorial you can find ) or just use this regex: str.matches("\\d+") (returns true if str is a number, but no comma here).
Of course, don't forget to cast your String as double after: Double.parseDouble( str.replace(",",".") );. I hope the "replace" part is obvious ;)
You might use the following snippet to read one double value:
Scanner scanner = new Scanner(System.in);
try {
double number = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}

Display an error message for the non-numeric input

So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();

Both next() and nextLine() not helping to store name with spacing

I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck

Categories

Resources