How to validate phone number - java

I am trying to validate phone numbers in java. In my country, phone numbers either begin with 9 or 8 and only have 8 numbers. I have done
try {
Integer.parseInt(phoneNo);
}
catch (NumberFormatException e) {
msg += "Plese enter amount in Integers.\n";
}
if (phoneNo.length() == 0)
msg += "Please Enter Phone Number.\n";
if (phoneNo.length() != 8)
msg += "Invalid Phone Number.\n";
However I need to validate when the first digit of the number isn't 9 or 8. I am not entirely sure of how I am supposed to do that. Please explain how your code works as I am a student and I am trying to learn.

Just in case you are looking for a regular expression solution.
You can do use the following pattern ^(?=(?:[8-9]){1})(?=[0-9]{8}).* to perform the check.
Essentially what it does is;
From first character position ^
Look ahead and see if the first character is a 8 or 9 (?=(?:[8-9]){1})
Then see if there are a total of 8 digits (?=[0-9]{8})
If the above conditions is a match then mark this as matched .*
public static void main(String[] args) {
String telephoneNr = "88765432";
if (telephoneNr.matches("^(?=(?:[8-9]){1})(?=[0-9]{8}).*")) {
System.out.println("Valid phone number!");
}
else {
System.out.println("Invalid!");
}
}
Output:
Valid phone number!

The methods that you need to put this together are readily available on the String and Character classes.
Here is an example program that does what you are looking for:
public class Foo {
public static void main(String[] args) {
// First try null and the empty string
System.out.println(isValidPhoneNumber(null));
System.out.println(isValidPhoneNumber(""));
// Now try an otherwise valid string that doesn't have the right first character
System.out.println(isValidPhoneNumber("01234567"));
// Now try an invalid string
System.out.println(isValidPhoneNumber("9a934581"));
// Finally a valid number
System.out.println(isValidPhoneNumber("94934581"));
}
static boolean isValidPhoneNumber(String phoneNo) {
// First validate that the phone number is not null and has a length of 8
if (null == phoneNo || phoneNo.length() != 8) {
return false;
}
// Next check the first character of the string to make sure it's an 8 or 9
if (phoneNo.charAt(0) != '8' && phoneNo.charAt(0) != '9') {
return false;
}
// Now verify that each character of the string is a digit
for (char c : phoneNo.toCharArray()) {
if (!Character.isDigit(c)) {
// One of the characters is not a digit (e.g. 0-9)
return false;
}
}
// At this point you know it is valid
return true;
}
}
The output it produces is:
false
false
false
false
true
The final for-each loop could avoid re-checking the first character by using a for loop with an explicit counter, but the performance gain of not checking a single int doesn't outweigh the cleaner code and better readability of the for each construct.
Edit: also please note that I removed the validation error messages from the original question for better readability as the OP asked to explain what the code was doing.

Instead of taking the phone number in a Integer variable take it in a String variable.
Then check whether the 1st number is 9, 8 or not by using stringVariable.charAt(0)
and for length of the phone number use int len=stringVariable.length();

You can check the first character of the phoneNo:
if (phoneNo.charAt(0) != '9' && phoneNo.charAt(0) != '8') {
// the first character is not a 9 or an 8
}
Documentation for charAt from Oracle.

Related

How to prevent integer input in Java?

I am trying to get my code to prevent a user input from having a number in it.
Essentially I want the code to do as follows:
ask for input
receive input
test whether or not the input contains a number(ex: 5matt vs matt)
if contains a number I want to System.out.println("Error: please do not input a number");
Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.
System.out.println("Please input the first name: ");
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();
name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();
I have this already but I can't figure out how to test if the input only contains letters.
Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods.
So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.
String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
System.out.println("Do not use digits!");
}
}
This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:
public boolean containsDigit(String text) {
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
return true;
}
}
// Iterated through the text, no digit found
return false;
}
And in your main program you call it this way:
String input = ...
if (containsDigit(input)) {
System.out.println("Do not use digits!");
}
Use a regular expression to filter the input
Eg
str.matches(".*\\d.*")
See this link for more info
There are several ways you could do this, among others:
Iterate over all the chars in the string and check whether any of them is a digit.
Check whether the string contains the number 1, number 2, number 3, etc.
Use a regular expression to check if the string contains a digit.
(Java Regular Expressions)
If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.
public static boolean stringHasDigit(String s) {
if (s == null) return false; //null contains no chars
else return stringHasDigit(s, 0);
}
private static boolean stringHasDigit(String s, int index) {
if (index >= s.length()) return false; //reached end of string without finding digit
else if (Character.isDigit(s.charAt(index))) return true; //Found digit
else return stringHasDigit(s, index+1);
}
Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

Java Password Checker

My problem is to create a password that contains between 6 and 10 characters and contains at least one letter and one digit, and then to have the user re-enter the password and confirm that they match.
The only issue I have is checking to see if the password has a letter or digit. I have browsed and found the same problem on the website, but I was confused about some of the methods and other things they referenced in their code since I seemed to build mine differently. I thought about using the indexOf() method to see if it returned a -1 value, but I'm not really sure where to begin.
I'm really new at java and I'm sure there is a much more efficient way to construct this, and I would love any tips.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
//Input from user
String password;
Scanner input = new Scanner(System.in);
System.out.print("Please create your password: ");
password = input.nextLine();
//Checking password length
while( (password.length() < 6) || (password.length() > 10) )
{
System.out.print("This password must be between 6 and 10 characters. Try again: ");
password = input.nextLine();
}
//Checking to see if passwords contain digit/letter
/*Need to add code here */
//Confirming if passwords match
String password2;
System.out.print("\nPlease type your password again to confirm: ");
password2 = input.nextLine();
while( !password2.equals(password) )
{
System.out.print("Those passwords do not match. Try again: ");
password2 = input.nextLine();
}
}
}
With Regex
You should use a regular expression, to check for theese crits.
First, the code:
pwd.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$")
Here's a full example:
public class HelloWorld{
public static void main(String []args){
String password = "aA2";
String regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$";
System.out.println(password.matches(regexp));
password = "12345678";
System.out.println(password.matches(regexp));
password = "aA345678";
System.out.println(password.matches(regexp));
}
}
gives the following output:
false
false
true
The regexp matches any string, that conatins at least upper case, one lower case letter and one digit, and 6 - 10 character long.
You can find more examples of theese here. And some info about the regexps on the Wikipedia. A very good tutorial about regexps and Java can be found on Vogella. (It's a very good site, with very good tutorials, I think!) And, a handy tool to display what a regexp matches: http://www.regexper.com/
In case of the previous example, it gives you a very visually output.
Without Regexs
So, if you cannot use Regulax Expressions, I would create a function, which returns true, if the password is OK, false in any other case. Here's a small example for this function:
public static boolean passwordOk(String password){
if (password == null) return false;
if (password.length() < 6 || password.length() > 10) return false;
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for(char ch: password.toCharArray()){
if(Character.isUpperCase(ch)) containsUpperCase = true;
if(Character.isLowerCase(ch)) containsLowerCase = true;
if(Character.isDigit(ch)) containsDigit = true;
}
return containsUpperCase && containsLowerCase && containsDigit;
}
The main idea thing in this solution, is a for-each loop. I create a character array from the String, and loop over the elements of it. If the current character is a digit, or uppercase, or lowercase, I set a flag, to sign, that one of the statements are true. At the beginning, all of the statements are false, and at the end I'll return the result of their sum.
In the first two lines I check, if the argument isn't null, and if it has the right length.
I hope, that after this you'll be able to solve your homework! You can call this function even with null pointers, so I would create a while loop, to run while this function do not returns true.
If it's hopeless, to solve this problem, here's the full code.
Believe me, it'll be more useful, if you try to solve this by your own, first!
You can use something like this...
if( password.matches(".*[a-zA-Z]+.*")){
System.out.println( "Has characters ");
} else {
System.out.println("Ok");
}
This is to check if the password contains a letter
Similarly you can use the regular expression ".*[0-9]+.*" to check if the password contains a digit.

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string
I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.
I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:
public void isValidCode(String subjectCode2){
str = subjectCode2;
if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
System.out.println("The code is valid");
}
else {
System.out.println("The code is not valid");
}
You can always use Regular Expressions, and the matches() method of the String class.
if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
// Validation succeeded
}
else {
// Validation failed
}
To test that the first three letters are letters, you could use a loop. Similarly, use a loop for testing that the last three digits are numbers. You might find the functions in the Character class helpful.
I would change the method signature so that it is not a void method but rather declared to return a boolean. Then you could have several if statements that if false returns false. At the bottom, return true if it passes all tests.
public boolean isValidCode(String code) {
if (code.length() != 6) {
return false;
}
// here check if first 3 chars are letters
// here check if last 3 chars are numbers
return true;
}
Then the calling code can do a println if desired.
String test = "ABC123";
if (isValidCode(test)) {
System.out.println("The code is valid");
} else {
System.out.println("The code is not valid");
}
If by "letter", you mean to include letters in alphabets other than English, you'll need this.
if (str.matches("\\p{L}{3}\\d{3}")) {
Here, \p{L} matches any character that Unicode considers to be a letter, in any language.

Java - See if a string contains any characters in it

The problem i'm having is when i check to see if the string contains any characters it only looks at the first character not the whole string. For instance I would like to be able to input "123abc" and the characters are recognized so it fails. I also need the string to be 11 characters long and since my program only works with 1 character it cannot go any further.
Here is my code so far:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
For instance why if i take away the checking to see the phoneNumber.length() it still only registers 1 character so if i enter "12345" it still fails. I can only enter "1" for the program to continue.
If someone could explain how this works to me that would be great
Your regex and if condition is wrong. Use it like this:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
This will only allow phoneNumber[a] to be a 11 character long comprising only digits 0-9
The + should be outside the set, or you could specifically try to match 11 digits like this: ^[0-9]{11}$ (the ^ and $ anchor the match to the start and end of the string).
You need to put the "+" after the "]" in your regex. So, you would change it to:
phoneNumber[a].matches("[0-9]+")
Why not try using a for loop to go through each character?
Like:
public static int phoneNumber(int a)
{
while (invalidinput)
{
int x = 0;
for(int i = 0; i < phoneNumber[a].length(); i++)
{
char c = phoneNumber[a].charAt(i);
if(c.matches("[0-9+]")){
x++;
}
}
if (x == phoneNumber[a].length){
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
Are the legal characters in your phone numbers 0..9 and +? If so, then you should use the regular expression [0-9+]*, which matches zero or more legal characters. (If not, you probably meant [0-9]+.) Also, you can use [0-9+]{11} instead of your explicit check for a length of 11.
The reason that your current code fails, is that String#matches() does not check whether the regular expression matches part of the string, but whether it matches all of the string. You can see this in the JavaDoc, which points you to Matcher#matches(), which "Attempts to match the entire region against the pattern."

Categories

Resources