How to validate user input in Java? [duplicate] - java

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
I'm trying to get user input and check if it is "1" or "2" and display an error messages if it's not. I keep getting error messages even when the input is correct.
Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!choice.equals("1") || !choice.equals("2"))
System.out.println("Invalid input. Give new value");
}while (!choice.equals("1") || !choice.equals("2"));```

Your condition is incorrect.
Use logical AND if need to eliminate both 1 and 2.
I think you wanted to achieve this
do {
choice = user_input.nextLine();
if (!choice.equals("1") && !choice.equals("2"))
System.out.println("Invalid input. Give new value");
} while (!choice.equals("1") && !choice.equals("2"));
Also to remove redundancy and improve the readability of code consider removing the validation logic to a separate method.
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String choice = "";
do {
choice = user_input.nextLine();
if (isValid(choice))
System.out.println("Invalid input. Give new value");
} while (isValid(choice));
System.out.println("Your input is valid: " + choice);
}
private static boolean isValid(String choice) {
return !choice.equals("1") && !choice.equals("2");
}

There's a logical error in the conditions. There should be "&&" instead of "||".
Thanks to #tgdavies.
Like this...
String choice = "";
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!choice.equals("1") && !choice.equals("2"))
System.out.println("Invalid input. Give new value");
}while (!choice.equals("1") && !choice.equals("2"));

if (!choice.equals("1") || !choice.equals("2")) doesn't make sense
I'm pretty simple minded, so I always like to do some simple checks, for example...
System.out.println(!true || !false); // !"1".equals("1") || !"1".equals("2")
System.out.println(!false || !true); // !"2".equals("1") || !"2".equals("2")
System.out.println(!false || !false); // !"3".equals("1") || !"3".equals("2")
Which prints
true // Show error message ... this is wrong, `1` is valid
true // Show error message ... this is wrong, `2` is valid
true // Show error message ... this is correct
which is obvious wrong, the first statement, we when not 1 or 2, print an error message
So, instead, we should invert the result of both sides of the ||, for example...
System.out.println(!(true || false)); // !("1".equals("1") || "1".equals("2"))
System.out.println(!(false || true)); // !("2".equals("1") || "2".equals("2"))
System.out.println(!(false || false)); // !("3".equals("1") || "3".equals("2"))
which prints...
false // Don't show error message ... `1` is valid
false // Don't show error message ... `2` is valid
true // Show error message ... `3` is invalid
Okay, that seems better
I'd also simplify the exit condition along the way...
Scanner user_input = new Scanner(System.in);
String choice = "";
boolean isValidChoice = false;
// Input Validation
do {
// Read user choice
choice = user_input.nextLine();
if (!(choice.equals("1") || choice.equals("2"))) {
System.out.println("Invalid input. Give new value");
} else {
isValidChoice = true;
}
} while (!isValidChoice);
System.out.println("Good choice!");

You can escape in the middle of the loop if the input is valid.
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String choice = "";
// Input Validation
while (true) {
// Read user choice
choice = user_input.nextLine();
if (choice.equals("1") || choice.equals("2"))
break;
System.out.println("Invalid input. Give new value");
}
}

Related

how to capture enter key when asking for integer input [duplicate]

This question already has an answer here:
hasNextInt() keeps waiting for input when pressing Enter
(1 answer)
Closed 11 months ago.
How do you capture the enter key when using hasNextInt()? I have the following code and am trying to exit gracefully if the user just enters the return key. In the example below I was expecting to get back -9, but the program just hangs on the hasNextInt() line
import java.util.Scanner;
public class InputInt{
public static void main(String[] args){
InputInt x = new InputInt();
System.out.println(x.enterInt());
}
public int enterInt(){
int myInt = -9;
boolean isValid = false;
String lf = "";
Scanner kb = new Scanner(System.in);
while(!isValid){
System.out.print("please enter an integer: ");
if(kb.hasNextInt()){
myInt = kb.nextInt();
isValid = true;
}else{
lf = kb.nextLine();
if (lf.length() == 0)isValid = true;
}
}
return myInt;
}
}
When asking for user input, always use nextLine(), which clears the input buffer (including the trailing newline), then check/parse the input for correctness:
while (true) {
System.out.print("Please enter an integer: ");
String input = kb.nextLine();
if (input.matches("\\d{1,8}")) {
myInt = Integer.parseInt(input);
isValid = true;
break;
} else if (input.ieEmpty()) {
break;
} else {
System.out.print("1 to 8 digits only please, or blank to exit.");
}
The final else is optional, but a nice touch.
The limiting of input to up to 8 digits means you'll never get a error on parsing. To allow every valid integer using regex, see this answer (it's ugly, so viewer discretion is advised).
Note also the more succinct and conventional while (true) with break combination, which obviates the need for overloading the isValid variable, which now means the user entered a valid integer.
To also allow negative numbers, use instead:
if (input.matches("-?\\d{1,8}"))

How to catch the error "InputMismatchException" in Java and print a personalized message , without using try and catch?

Scanner sc = new Scanner (System.in);
int source_radix = sc.nextInt();
String sr = source_radix+"";
if (!Pattern.matches("[0-9]+",sr) || source_radix <1 || source_radix >36)
{
System.out.print("error");
System.exit(0);
}
I want to print "error" when the input is not an integer.
The simplest way to prevent that exception being thrown from nextInt() is to call hasNextInt() first. In your specific example, we could do this:
Scanner sc = new Scanner (System.in);
int radix = 0;
if (sc.hasNextInt()) {
radix = sc.nextInt();
}
if (radix < 1 || radix > 36) {
System.out.print("error");
System.exit(0);
}
You could modify that to print different error messages to distinguish the cases where the user didn't enter a valid integer, and where they entered a integer that was outside of the required range.
In some situations, it may be necessary to call sc.nextLine() to discard something that isn't a valid number, or anything on the line after the number. (But it isn't necessary if the app is going to terminate on getting bad input.)
Finally, it is often a bad idea to call System.exit(0). If this is in your main method, return will work just as well. If it is not in main, then it probably should not be this code's responsibility to "pull the plug" on the application. But ... it is not clear cut.
You can do something this:
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
String str =sc.nextLine();
if (!Pattern.matches("[0-9]+",str) ||( Pattern.matches("[0-9]+",str) && Integer.parseInt(str)) <1 )|| ( Pattern.matches("[0-9]+",str) && Integer.parseInt(str)) <1 ) >36) {
System.out.print("error");
System.exit(0);
}
}
You can check if input is number of range from 1 to 36 by only using Regex:
Scanner sc = new Scanner(System.in);
String sr = sc.nextLine();
if (!Pattern.matches("[1-9]|[12][0-9]|3[0-6]", sr)) {
System.out.print("error");
System.exit(0);
}
You may try this Java code:
Scanner sc = new Scanner (System.in);
String sr = sc.next(); // read a string
// check if we have all digits in input
boolean match = Pattern.matches("[0-9]+", sr);
// if yes then convert to int and do comparison
if (match) {
int source_radix = Integer.parseInt(sr);
if (source_radix <1 || source_radix >36) match = false;
}
// handle error if match is false
if (!match) {
System.out.print("error");
System.exit(0);
}

What possible exceptions are there if User enters String instead of Int?

I am just playing with Java.I'm trying to force my program to only accept number digits 1 and 2. I believe I have successfully done this using a while loop (please correct me if I'm wrong). But how do I go about printing an error statement if the user enters a string. eg: "abc".
My code:
while (response != 1 && response != 2) {
System.out.println("Please enter 1 for Car or 2 for Van: ");
response = scan.nextInt();
}
if (response == 1) {
vehicleType = VehicleType.CAR;
while (numPassengerSeats < 4 || numPassengerSeats > 7) {
System.out.println("Please enter the number of Passengers: ");
numPassengerSeats = scan.nextInt();
}
} else {
vehicleType = VehicleType.VAN;
while (true) {
System.out.println("Please enter the last maintenance date (dd/mm/yyyy): ");
String formattedDate = scan.next();
lastMaintenanceDate = formatDate(formattedDate);
if (lastMaintenanceDate != null)
break;
}
}
Let's have a look at javadoc for nextInt():
Scans the next token of the input as an int. An invocation of this
method of the form nextInt() behaves in exactly the same way as the
invocation nextInt(radix), where radix is the default radix of this
scanner.
Returns: the int scanned from the input
Throws:
InputMismatchException
- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
As per javadoc, it throws InputMismatchException if the user enters a String instead of an int. So, we need to handle it.
I think you have not successfully force your program to accept just integers since by using java.util.Scanner.nextInt(), user can still be able to input non integers, however java.util.Scanner.nextInt() will just throw an exception. Refer to this for possible exception thrown.
I have made a solution to force your program to accept just integers. Just follow the sample code below:
Sample code:
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int response = 0;
Scanner scan = new Scanner(System.in);
while (response != 1 && response != 2) {
System.out.println("Please enter 1 for Car or 2 for Van: ");
try {
response = Integer.parseInt(scan.nextLine());
if (response != 1 && response != 2) {
System.out.println("Input is not in choices!");
}
} catch (NumberFormatException e) {
System.out.println("Input is invalid!");
}
}
scan.close();
}
}

Incompatible operand types String and int

Just a code of a bank with few functions, I am only trying to learn the way if loops are made. Seem to be getting "Incompatible operand types String and int" error on all lines that have an if,else if.
import java.util.Scanner;
public class Bank
{
//create variables
int pac;
int confirm;
int pin;
int Bal_or_Exit;
public static void main(String args[])
{
//Receive any PAC and create if loop for continue or exit
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your Personal Access Code (P.A.C)");
String pac = in.nextLine();
System.out.println(pac + " is the P.A.C you have just entered.");
System.out.println("Press 1 to continue, Press 2 to cancel");
String confirm = in.nextLine();
if(confirm == 1)
//if loop created for confirm or exit...create another if loop for a pin of 0207
{
System.out.println("Please Enter your Pin");
String pin = in.nextLine();
if(pin == 0207)
//if loop created for pin, only access if pin=0207..access granted and
option of viewing Account Balance or Exit
{
System.out.println("Welcome!");
System.out.println("Press 1 for Balance");
System.out.println("Press 2 to Exit");
String Bal_or_Exit = in.nextLine();
//if 1 is pressed, display balance of €2965.33
if(Bal_or_Exit == 1)
{
System.out.println("Your balance is €2965.33");
}
//if 2 is pressed, display goodbye message
else if(Bal_or_Exit == 2)
{
System.out.println("GoodBye, Have a Nice a Day!");
}
//if anything else is pressed display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
//if pin is anything except 0207 , display wrong pin message
else
{
System.out.println("The PIN you Have entered is incorrect");
}
}
//if confirm = 2 (exit), display exit and goodbye message
else if(confirm == 2)
{
System.out.println("You have selected exit");
System.out.println("Have a Nice Day!");
}
//if confirm is not = 1 or 2, display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
}
You have that error due to Scanner#nextLine() returns a String, so, when you call:
String confirm = in.nextLine();
confirm is a String and then you're trying to compare:
if(confirm == 1)
In other words:
if (String == int)
You should either:
Call Scanner#nextInt()
Change your if as follows:
if (confirm.equals("1"))
There are multiple problems with your code. Take if(pin == 0207) as an example:
pin is a string so it can't be compared to a number like that
strings need to be compared via equals() and not ==
0207 is an octal literal, i.e. in decimal it would be the number 135.
To fix that change pin == 0207 to pin.equals( "0207" ) and the other string comparisons such as confirm == 1 accordingly too.
You could also try to parse the strings to numbers, e.g. Integer.parseInt( confirm) == 1 but since 0207 is probably meant to be used as it is you need to use String here anyways.
You can't compare a string with an integer because they are two different data types. You will have to cast the string to an integer to do this.
Like this:
if(Integer.parseInt( confirm ) == 1)
Alternatively you can cast the user input before storing it in the string variable.
int confirm = Integer.parseInt(in.nextLine());
You can also read the user input as an integer instead of a string.
int confirm = in.nextInt();
For the value 0207 it would be more sensible to compare it as a string because of the leading 0. This information would get lost if you compare it as an integer. To compare strings you can use the equals() method.
if(pin.equals("0207"))

Using exception handling to force user to input a char (letter) instead of String in Java

Say I had some code like:
Scanner scan = new Scanner(System.in);
System.out.print("Please input a letter: ");
char userLetter = nextLine().charAt(0);
I'd like to use exception handling to make sure the user only inputs a letter and nothing more. Is there a good way to do this?
If you need to introduce exception handling here is what I would do:
Scanner scan = new Scanner(System.in);
char c;
while(true) {
System.out.print("Please input a letter: ");
try {
String s = scan.next();
if(s.length() > 1) {
throw new RuntimeException("Input too long!");
}
c = s.charAt(0);
if (Character.isLetter(c)){
throw new RuntimeException("Char is not a letter!");
}
// here you can break the loop and do whatever
} catch(RuntimeException re){
System.out.print(re.getMessage());
// you can break the loop or try again
}
}
P.S. In real-world applications using exceptions for controlling the flow of execution is considered a bad practice. So keep in mind that this code should be used only as an exercise.
Frankly, I wouldn't use exceptions in this situation. There's nothing "exceptional" going on - just the user providing the wrong input. You can check it and prompt the use to input something different:
Scanner scan = new Scanner(System.in);
System.out.print("Please input a letter: ");
String line = nextLine();
while (line.length() != 1 || !Character.isLetter(line.charAt(0))) {
System.out.print("That's not a letter. Please try again: ");
String line = nextLine();
}
If the throwing of exception is required you could do something like this:
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(input.length() != 1){
throw new Exception("...");
}
char userLetter = input.charAt(0);
I think this should work.
You could check the length of the String and if it is greater than 1, :
String s = null;
do{
System.out.println("Enter Character : ");
s = scan.next();
if(s.length()!=1)
System.out.println("Error");
}while(s.length()!=1);
System.out.println(s.charAt(0));
If needed, you could add another check for Character#isLetter.
Exceptions should not be used for circumstances that might happen too often.... Instead, we should use if...else to handle regularly occurring situations...
Why don't you use something like this:-
Scanner input = new Scanner(System.in);
String text = new String();
do {
System.out.print("Type a character: ");
text = input.nextLine();
if(text.length() > 1) {
System.out.println("Kindly enter only one character...");
}
} while(text.length() > 1);

Categories