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.
Related
The idea is that the while loop should loop through the code if the result is "wrong password",
until the correct password is entered and breaks the loop when it matches the login method return value.
while (true){
System.out.println("\nLogin: ");
System.out.println("\nEnter a username: ");
String loginUsername = sc.nextLine();
System.out.println("Enter a password: ");
String loginPassword = sc.nextLine();
System.out.println(login(loginUsername,loginPassword));
if (login(loginUsername,loginPassword).equalsIgnoreCase("Successfully logged in!")) {
break;
}
}
this code is the return statements from the login method
if (check == true){
return ("\nSuccessfully logged in!");
} else {
return ("\nWrong username/password");
}
But "Successfully logged in!" is not the same string as "\nSuccessfully logged in!".
More importantly... Why use strings for this at all? If you want to know whether something is true or false, there's a perfectly good data type to convey that information. Return that type instead:
return check;
Rename the method to something more meaningful than login, and use its result in a semantically clear condition:
if (isLoginSuccessful(loginUsername,loginPassword)) {
break;
}
This puts the semantics of what you're doing in the code itself, rather than in magic strings that you need to copy/paste everywhere and manually keep track of. Which, already in this one tiny example, you've lost track of by making the strings different. (With the added benefit that using booleans for conditional logic probably performs a little better than string comparison.)
I'm fairly new to java and was wondering how would one force a user to enter a valid option in a do...while loop?
What i'm trying to achieve here is to display a menu for as long as the user does not select the exit option which is '4' in my case (it's a char not an int). But if the selection is invalid I want to display an error message and prompt the user to make a new selection, this time, without displaying the menu again.
So far, inside my do...while loop i'm displaying different information according to the user selection. If they enter anything other than 1-4, they end up in my last else if which displays an error message, but at the same time they leave the if/else if loop and end up back in the main menu.
Don't know if this is clear but any help would be appreciated. I also tried the same thing with switch but got the same problem.
Thanks.
do {
// display main menu
if (menu == '1') { ... }
else if (menu == '2') { ... }
else if (menu == '3') { ... }
else if (menu == '4') { ... }
else if (menu != '4') { // display error message }
} while (menu != '4')
Okay, so you have a job which we can describe in a self-contained fashion with a short list of clearly stated parameters:
Ask the user for input.
Check that the input is valid.
If not, keep asking.
That's it. That's a job we can write. Easily at that.
So, do that! Make a method to do just this job. There's only one parameter you need, which is: "What constitutes valid input". If we can simplify that we just need a character, and everything from '1' to this char is valid, then:
public char askUser(char maxValid) {
do {
char in = askUserForInput(); // however you get that char.
if (in >= '1' || in <= maxValid) return in;
System.out.println("Enter a value between 1 and " + maxValid + "> ");
} while (true);
}
Then you can just call this method when you need input.
You can roll this logic (so, that'd be a do/while loop inside your do/while loop) into the main loop, but two rather significant aspects of writing good code is to find easily isolatable aspects and to, well, isolate them (be it making new methods, types, modules, or subsystems - it applies across the entire hierarchy), and to avoid repeating yourself.
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.
I am using validation on my jsp page . when an entry in a field is not acceptable we currently give generic error messages like "Please enter a valid number" but i want show like which character i have entered is not numeric. example: suppose if I enter "O" instead of an "0" , i want to show messages "O" is not acceptable as number
How can I achieve this.Any ideas and guidelines would be appreciable
Okay, this is achieved easily. We all know we can use multiple validation messages in one property, right? Ex:
[Required(ErrorMessage = "link is wrong!")]
[DisplayName("link (ex: http://test.com)")]
[Url(ErrorMessage = "Please write a valid link!")]
public string Linku { get; set; }
So, now all you have to do, is take some of your time and add as much as you need. You can add extra attribute on te previous example, and add one more case exactly as you needed it, ex:
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "You cant add numbers on the link field")]
[Required(ErrorMessage = "link is wrong!")]
[DisplayName("link (ex: http://test.com)")]
[Url(ErrorMessage = "Please write a valid link!")]
public string Linku { get; set; }
As i see, the main purpose of you is this attribute to take some parameter, and show him more dynamically on what he wrote, that is not right. But exaclty like that, attribute validation does not offer us something which is prepared. If we want to go that deep, we have to do it in our controller when we check:
if(ModelState.IsValid)
{
//here we can edit validation error messages, since we can have
//parameters from the controller right?
}
Also, you can check error messages, and maybe edit them inside this for loop.
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
DoSomethingWith(error);
}
One more option is doing it with javascript/jquery, client side validation, which is not very useful when its up to security, and bypassing.
Here a quick exemple of how you can get all characters who dont fit your need. You may have to adapt it to your code. It is just a guideline.
String test="456464O1324l456";
ArrayList<Character> chars=new ArrayList<Character>();
for (Character c: test.toCharArray()) {
boolean error=Character.isAlphabetic(c);
if(error){
chars.add(c);
}
}
for (Character character : chars) {
System.out.println(character);
}
I am building an application where I have a server and a client that talk to each other -over telnet. (via socket). The server program is monitoring a tank of some gass, and sends temperature level and preassure level via socket to the accepted clients.
I have managed to get the client and server to talk to each other when I write stuff --in telnet--, but...
I need some help to handle the data that I send.
I have made a loginscript to determine if the user is a valid user or not.
So I can write two words like "myname" "space" "mypassword" and I get a green light and returns a valid user.
But when I only write one word, and hit enter, it gives me:
Exeption in thread... java.lang.Array.IndexOutOfBoundsExeption EXEPT for when I write exit or logout!
(All users are hardcoded in the script for ease of use for testing. (The login script works fine by it self, and returns valid user = false when I write something wrong.)
Here is my code. Some pseudo code is added since I am not 100% sure of what to do...;)
String telNetCommand = dataIn.readLine();
System.out.println(telNetCommand);
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
if (dataInArray[1] == "\n") {
//Ignore login request and continue telnet-logging?
}
The client application has a button for each command, like:
"Send me every n'th data", or "Send me a batch of data every n'th second. If command equals exit, or logout - > break operation....
// --------------// USER INPUT FROM CLIENT APP //--------------------------//
// --------------// CONTINUE ? //----------------------------//
if (command.equals("CONTINUE")) {
continueSession();
else { //..Kill session
}
}
// --------------// SKIP <N> //----------------------------//
if (command.equals("SKIP_N")) {
skipEveryNthData();
}
// --------------// BATCH <N> //---------------------------//
if (command.equals("BATCH_N")) {
batchEveryNthData();
}
// --------------// LOGG OUT #1 //-------------------------//
if (command.equals("logout") || command.equals("exit")) {
break;
}
Maybe I am getting a bit confused now, but I think that I need to put all data into an array, and check
if
dataInArray[0] == "CONTINUE"
dataInArray[0] == "SKIP_N", or
dataInArray[0] == "BATCH_N"
(then send some data back)...
and...
if dataInArray[1] == "enter" ("\n") execute the single word commands ...??
if dataInArray[0] == "LOG_IN" or "PASSWORD" check if valid user is true..
Thanks for any help, and/or tips! :)
In this part of your code:
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
You assume that the telNetCommand string contains a space. If it does not, dataInArray will only contain one element and dataInArray[1] will throw an IndexOutOfBoundsExeption.
You should check the size of the array:
if (dataInArray.length < 2) {
//no space in the command - do what you need to do
//for example an error message
}
The IndexOutOfBoundsExeption more than likely being caused by:
user.isValid(dataInArray[0], dataInArray[1]);
Make sure that the incoming String telNetCommand contains at least one space so that you have at 2 Strings in the array. You could do this checking the size of the array:
if (dataInArray.length < 2) {
throw new IllegalArgumentException(telNetCommand + " only contains " + dataInArray.length + " elements");
}
Also, on a different note, make sure to use String.equals when checking String content:
if ("\n".equals(dataInArray[1])) {
Thanks guys. I don't get any errors now... And here is what I ended up doing.
I had to set it == 2 in order not to get any errors.
while (true) {
String telnetCommand = dataIn.readLine();
System.out.println(telnetCommand);
String dataInArray[] = telnetCommand.split(" ");
if (dataInArray.length == 2) {
user.isValid(dataInArray[0], dataInArray[1]);
}
if (dataInArray.length < 2) {
if (telnetCommand.equals("CONTINUE")) {
continueThisSession();
System.out.println("Running method continueThisSession");
}
if (telnetCommand.equals("SKIP_N")) {
skipEveryNthData();
System.out.println("Running method skipEveryNthData");
}
if (telnetCommand.equals("BATCH_N")) {
batchEveryNthData();
System.out.println("Running method batchEveryNthData");
}
if (telnetCommand.equals("logout") || telnetCommand.equals("exit")) {
break;
}
}
}
Peace :)