Exception handling when dealing with user input for a beginner - java

I have to do a little program based in a shop, I have to add new clients to the shop customer collection, new items to the shop stock, edit them etc, so I use user input(scanner) to create this new objects. I have all the methods I need for this already without exceptions.
I would like some simple java exception handling for when the user introduces a string were he is supposed to enter a integer or viceversa.
For example if I'm executing a method to create a item for the shop and when I ask the user to introduce the stock(integer) the user types hello instead of a number the program crashes, I would like to handle the exception, show a error message, don't create the object and relaunch the item creation method from the beggining(or relaunch the submenu it was right before)
should I use try and catch? the method in try, when it fails catch throws message of error and relaunches the item creation menu? How should i do this? I've been searching and found a interesting method for integers here:
Exception Handling for no user input in Java
The problem is I don't know how I could handle possible exceptions for when introducing the ID for the user(which would be a string composed of 8 numbers and a letter like for example: 13234354A, so how could I show a error if a user introduces "sjadsjasdj" as a ID instead of something sort of realistic ) or some other things like handling exceptions for a few enum or boolean variables I use when creating this objects.
I've been looking in this site and searching google but I haven't found what I need or are more complex than what I understand with my little knowledge, also English is not my native language so my searches may be a little off.
Thanks for your time!

When you are reading the input just read in the the entire ID 123A for example and verify that each character is valid using for example Character.isDigit() and Character.isLetter(). With a 4 letter case
import java.util.Scanner;
public class Test {
public static void main(String[]args) {
boolean flag = false;
Scanner kb = new Scanner(System.in);
while(!flag) {
String id = kb.next();//To get the next word
flag = true;//by default its assumed to be valid input
if(id.length() == 4) {
for(int i = 0; i < 3; i++) {
if(!Character.isDigit(id.charAt(i))) {
flag = false;
}
}
if(!Character.isLetter(id.charAt(3))) {
flag = false;
}
}
else {
flag = false;
}
System.out.println("ID is "+ (flag == true?"Valid":"Invalid"));
}
}
}
Output
1234
ID is Invalid
123A
ID is Valid
You could throw your own error at the end if you want or just loop back to the beginning to take a new input.

Related

Storing text as an arraylist from JTextArea

I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}

How to get all required strings in a string array before a break

We were given a task to make a program that takes the input of the user. there two types of input the user can use, 1st is the "Type in the Size" and the second is "Type in the style" either way the user can just input in the 1st field or the 2nd field. when the users clicks ok the two inputs will be use to sortout a arraylist which contains the type of size and style in it.
public void viewResult(String style, String size) {
style = style.toLowerCase();
size = size.toLowerCase();
new_list = new ArrayList<>();
for(Items_container items:current_arrayList)
{
if (items.getStyle().toLowerCase().contains(style) && items.getSize().toLowerCase().contains(size))
{
new_list.add(items);
break;
}
else if (items.getSize().toLowerCase().contains(size)) {
new_list.add(items);
break;
}
else if (items.getStyle().toLowerCase().contains(style)) {
new_list.add(items);
break;
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
if (new_list.size() == 0) {
results.setText("Search not found");
} else {
results.setText("Results");
}
}
this is the method that I use to sortout out the Items_container now it does work fine (I guess)
but the problem is for example the user inputs "large" in the size input field and "blazzing" in the style input field the program must sort the items_container using the given inputs but it is not working because the program also includes all the items that has the same size or the same style.
I tried adding a break to the loop but now it only shows one data and what if there two or more data that matches the givens inputs, how can I do that?
You should check first if both conditions are set. That way you can separate if either one matches and if both match. Maybe put singular matches in a separate list in case no items match both conditions, but that's up to you.
And as others already said, break stops the loop, continue moves to the next item.
like code below:
for (int i = 0; i <current_arrayList.size() ; i++) {
if(current_arrayList.get(i).getStyle().toLowerCase().contains(style)
&& current_arrayList.get(i).getSize().toLowerCase().contains(size))
{
new_list.add(current_arrayList.get(i));
//if used break ,stop loop
}
else if (current_arrayList.get(i).getSize().toLowerCase().contains(size)) {
new_list.add(current_arrayList.get(i));
}
else if (current_arrayList.get(i).getStyle().toLowerCase().contains(style)) {
new_list.add(current_arrayList.get(i));
}
}
current_arraylist.clear();
adapter.filterSearch(new_list);
adapter.notifyDataSetChanged();

Multiple error notifications

I have a registration page where the user has to enter personal information about themselves, if something entered is invalid then error notifications should pop up
if (!PhoneNumber.startsWith("055") || !PhoneNumber.startsWith("050") || !PhoneNumber.startsWith("056") || !PhoneNumber.startsWith("052")) {
// does not match
contact_number.setError("Please enter a valid phone number");
return;
}
if (TextUtils.isEmpty(password) )
{
VendorRegPassword.setError("Please enter your password");
return;
}
else if (password.length() < 6)
{
VendorRegPassword.setError("Please use more than 6 characters");
return;
}
if (TextUtils.isEmpty(email) || !email.contains("#") )
{
VendorRegEmail.setError("Please enter a valid email address");
}
Independently they work on their own but when put together it does not work properly, also the phone number error does not work properly, can somebody help me with this?
The other answer is correct; the return statement simply prevents all checks to be executed. And in this case, you want all validations to take place, as each validation has a different way of informing the user about the problem.
Beyond that: from a "clean code" perspective you should be careful to simply stuff all validations into the same poor method. Instead: structure your code so that it clearly expresses what is going on, like:
private void validateAll(PhoneNumber number, Email email, Password password) {
validatePhoneNumber(number);
validateEmail(email);
...
and separate helpers like
private void validatePhoneNumber(number) {
boolean validPrefix = false;
for (String validPrefix : PREFEIXES) {
if (phoneNumber.startsWith(validPrefix) {
validPrefix = true;
}
}
if (!validPrefix) {
contact_number.setError("Please enter a valid phone number");
}
}
for example. And please note - I fixed another bad practice (your idea to simply hard-code all valid prefixes). You always want to put such information into some constant set/list; so that you have exactly one place in your code that knows what those prefixes are.
They are not working together properly because you are returning from the method in if or else ifconditions. Remove return statements from if and else. Because return will terminate the execution of method, so further code will never be executed due to return.
They are working separately because, there is no need to execute further conditions (no further conditions at all), so returning from method seems correct solution.

Java user input validations

I'm new to Java GUI . I'm doing a project using Netbeans.There are several text fields and I need to do validations for them.
Validations should be
Want to check whether fields are empty or not.
If it's a number field it should be validated only to input numbers.
In web (Ex:contact form) validations we can validate the fields step by step when user is entering data up to down. I need to know whether it is possible or not in Java GUI programmes.
Found several methods as Documentfilter,InputVerifier and PlainDocument. Can someone please explain the differences of them and what is the best method to use for validations input data of users in Java?
depending how familiar you are with java programming in general, this helps you more or less
Retrieve the text from the JTextField (getText()) and check for emptiness
Cast the text to a number and catch a NumberFormatException in case its not a number.
for 2) its a validation after the user has entered something and not an validation during typing
You should write java method for validation .
1.Read Text from JTextField using (getText() ) and pass this string to NumberValidation Method . Sample code is shown below
String data=textFieldObject.getText().trim();
boolean validate =isValidMobile(data);//return false if the data is not a valid phone number
public boolean isValidMobile(String PhoneNumber)
{
try{
if(PhoneNumber.length()==10) //checking length.
{
for(int i=0;i<10;i++){
char c=PhoneNumber.charAt(i);
if(!Character.isDigit(c)) //return false if the character is digit
{
return false;
}
}
}else
{
return false;
}
return true;
}catch(Exception r)
{
return false;
}
}

Input validation without using try catch exception

Im writing a program that calculates the investment of a person after a number of years. I prompt the users to enter their name, amount they will be investing, interest rate, and number of years. I'm supposed to do a validation of the input with if...else statements. One of the checks is to see if the user has entered the correct data type. This is for an intro java class. We finished the chapter on methods a week ago, so this is beginner's stuff. I can seem to figure out how to do the data type check. I tried the hasNextInt for my int types but I get an exception which we haven't learned at all. I found some info online on the Pattern and Match classes but there's a lot of stuff in there that we haven't seen yet. Here's one of the methods I wrote to get the correct input.
//Define method for input validation, integer type
public static int getValidInt(String messagePrompt, String messagePrompt2, String messagePrompt3){
Scanner input = new Scanner(System.in);//Create scanner
int returnValue;
int j = 0;
do {//Start validation loop
System.out.printf(messagePrompt); //Print input request
returnValue = input.nextInt();
if (returnValue <= 0) { //Check if user entered a positive number
System.out.println(messagePrompt2);//Print error message
}
else if (!input.hasNextInt()) {
System.out.println(messagePrompt3);//Print error message
}
else {
j++;
}
} while (j == 0);//End validation loop
return returnValue;
}
Im not sure if I have the order of the checks right. Any help is welcome. Thank you.
If it's just 4 pre-defined input fields and you don't have to check for additional things then I don't see a reason to use a do while loop here. Though maybe I don't get what this method is supposed to do, are you returning some kind of integer that defines whether the input was valid or do you actually have to store the values? If the former, why not just return a Boolean or an Enumeration?
I also don't understand why you're simply calling nextInt the first time, but for the next one you are checking whether it has a nextInt.
Also you don't mention what kind of exception you're getting when calling hasNextInt, but apparently this can only be an IllegalStateException. I suggest taking a look at the Java docs at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html, or reading your relevant course material.
The sequence nextInt() and hasNextInt() is invoked. First one is used to read the value from input, and second is used to see whether the value type is int. So you have to invoke hasNext[Type]() followed by next[Type].
Let's correct those two first as below.
if (scnr.hasNextInt()) {
int userChoice = scnr.nextInt();
} else {
// input is not an int
}
Now let's correct your code to get a valid int.
public static int getValidInt(String messagePrompt, String messagePrompt2, String messagePrompt3) {
Scanner input = new Scanner(System.in);// Create scanner
int returnValue = -1;
boolean incorrectInput = true;
while (incorrectInput) {
System.out.printf(messagePrompt); // Print input request
if (input.hasNextInt()) {
returnValue = input.nextInt();
if (returnValue <= 0) { // Check if user entered a positive number
System.out.println(messagePrompt2);// Print error message
} else {
incorrectInput = false;
}
} else {
input.next();
System.out.println(messagePrompt3);// Print error message
}
}
return returnValue;
}

Categories

Resources