I have simple java program that accepts 3 user inputs of type integer, double and string. I would like to know the best/most efficient way to perform error handling on all of these inputs in order to keep the program running, inform the user they have entered an incorrect input and ask them the question again . Any help would be greatly appreciated.
Here is my code
Scanner scan = new Scanner(System.in);
int inputInt;
double inputDbl;
String inputString;
System.out.print("Please enter a whole number: ");
inputInt = scan.nextInt();
System.out.print("Please enter a decimal number: ");
inputDbl = scan.nextDouble();
System.out.print("Please enter a string: ");
inputString = scan.next().toLowerCase();
Thanks for all the input people, you guys are awesome. I chose to just use a simple dowhile loop using a boolean trigger. I've tried using try catches before but ended up writing huge blocks of code to perform very basic input checks. So don't have any exception handling here, which I hope isn't gonna be necessary this way. Hopefully it doesn't break on me
do {
System.out.print("Please enter a whole number: ");
if (scan.hasNextInt()){
inputInt = scan.nextInt();
validInput = true;
} else
System.out.println("You have entered incorrect input! Please enter a whole number only");
scan.nextLine();
} while (validInput == false);
validInput = false;
do {
System.out.print("Please enter a decimal number: ");
......
......
Splitting this into n methods where n is how many user inputs there are.
For each user input create a method that gets the input:
String getStringInput(){
System.out.println("Enter input");
String input = scan.next();
//check the input to make sure it is correct
if(input.equals("foo")){
//if the input is incorrect tell the user and get the new input
System.out.println("Invalid Input");
//simply return this method if the input is incorrect.
return getStringInput();
}
//return the input if it is correct
return input;
}
For the main method that gets the input simply call the method:
void getAll(){
String stringValue = getStringInput();
}
This now makes it easy to get any number of inputs and check if the are correct.
boolean validated = false;
// this keeps user locked until he/she provides valid inputs for all variables
while(!validated) {
//get inputs here
// ..
// lastly
validated = validateLogic(inInt, inDbl, inStr);
}
// keep going
If you want to validate separately for each input, you shuold write while loop 3 times.
Related
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 3 years ago.
I have to make a store that has items for purchase. After choosing an item, I prompt the user to enter the quantity of the item they would like to buy.
// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();
If the user enters a non-integer (i.e. decimal, char...), it breaks the program.
Is there a way I can validate for this non-integer input?
Thank you
Sure, accept a String value instead of an int, check to see if you can parse that String value to an int, if you can, then do so. If not, sent a message stating that then entered value must be an number.
This could be done in a while loop.
import java.util.Scanner;
public class ScannerInputInt {
public static void main(String... args) {
Scanner in = new Scanner(System.in);
Integer input = null;
do {
System.out.println("Please enter number: ");
String s = in.nextLine();
try {
input = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("ERROR: " + s + " is not a number.");
}
} while (input == null);
}
}
If you don't wanna use Exceptions method. You can try this.
This piece of code will continue to ask user input until user has entered correct input.
System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
input.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();
Output:
Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2
I think it is slightly better approach because I think controlling flow of your program with Exceptions is bad practice and should be avoiding when there are other things that you can use.
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);
I am having problems with my program. Everything is running smoothly, however, when the user inputs the wrong variable it does display the right feedback, but the user then has to enter one extra variable than previously stated.
Maybe it's a simple mistake I have made, but I can't see it..
It's confusing. An example when I run the program:
How many grades would you like to average?
3
Please enter 3 grades:
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number:
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3
Your average is: 96.67
The second 100 input in the console should not appear, but it does when the user has at least one input error. If I were to run the program and input all the correct variables, then the program works smoothly.
This error also occurs when asking for how many grades the user would like to average. I thought it'd be easier to view what's wrong with my program by the second part.
I'm trying to get this program to run smoothly. Help is appreciated!
for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
// Check if the input variables are numerical variables
while (!input.hasNextDouble()) {
input.next();
System.out.println("You've entered a non-numerical variable. Please enter a number: ");
while (input.nextInt()<= 0){
System.out.println("You've entered a negative number. Please eneter a positive number: ");
}
}
// Read grade input
gradesInput = input.nextDouble();
Instead of input.hasNextDouble() you can try below
Scanner scan = new Scanner(System.in);
System.out.print("Enter total no of input ");
int total = Integer.parseInt(scan.nextLine());
int[] input = new int[total];
for (int i = 0; i < total; i++) {
while (true) {
try {
System.out.print("Enter number ");
String in = scan.nextLine();
input[i] = Integer.parseInt(in);
break;
} catch (RuntimeException re) {
System.err.print("Invalid input. ");
}
}
}
scan.close();
System.out.println(Arrays.toString(input));
It'll force the user input only numbers, you can add boundaries or change data type if required.
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}