Java: checking if a phone number fits a valid format - java

I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}

It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}

If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.

It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}

Related

Exception in thread "main" java.lang.NumberFormatException: For input string: "/3"

Below are the code. To fix the error, I simply rewrote the code in getFraction() method to den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/")+1, fracValue.length())) , by adding +1. I have never seen or learn this during my courses and I just encounter this while doing project. I want to understand what the code did in num = Integer.parseInt(fracValue.substring(0, fracValue.indexOf("/"))) and den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/"), fracValue.length())), we are converting the numerator to int and the num is all the values before the / and the den is all the values after the /. Am I right ? My second question is that why do we need to add +1 after the indexOf("/") ? Is it so we are taking the values after the /?
import java.util.Scanner;
public class FractionCalculator {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
intro();
while (true) {
String operation = getOperation();
Fraction frac1 = getFraction();
Fraction frac2 = getFraction();
Fraction result = new Fraction(1,1);
String result2 = "";
if (operation.equals("=")) {
System.out.println(frac1+" "+operation+" "+frac2+" is "+frac1.equals(frac2));
} else {
if (operation.equals("+")) {
result=frac1.add(frac2);
} else if (operation.equals("-")) {
result=frac1.subtract(frac2);
} else if (operation.equals("/")) {
if(frac2.getNumerator()==0) {
result2="Undefined";
} else {
result=frac1.divide(frac2);
}
} else if (operation.equals("*")) {
if(frac2.getNumerator()==0) {
result2 = "Undefined";
} else {
result=frac1.multiply(frac2);
}
}
//print results
} if (result2!="") {// division and multiplication by zero is undefined
System.out.println(frac1+" "+operation+" "+"0"+" = "+result2);
} else if (result.getNumerator()%result.getDenominator() == 0) {
System.out.println(frac1+" "+operation+" "+frac2+" = "+(result.getNumerator()/ result.getDenominator()));
} else {
System.out.println(frac1+" "+operation+" "+frac2+" = "+result.toString());
}
}
}
public static void intro() {
System.out.println("\nThis program is a fraction calculator");
System.out.println("It will add, subtract, multiply and divide fractions until you type Q to quit.");
System.out.println("Please enter your fraction in the form a/b, where a and b are integers.");
for (int i=0; i<80; i++) {
System.out.print("-");
}
}
public static String getOperation() {
System.out.println("\nPlease enter an operation (+, -, /, *, = or \"Q\" to quit): ");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
int x = 0;
while (x == 0) {
if (operation.equals("+") || operation.equals("-") || operation.equals("/") || operation.equals("*") || operation.equals("=")) {
x++;
} else if (operation.equalsIgnoreCase("q")) {
System.exit(0);
} else {
System.out.println("Invalid input, enter valid operation (+, -, /, *, = or \"Q\" to quit)");
operation = input.nextLine();
}
}
return operation;
}
public static boolean validFraction(String input) {
boolean valid;
if (input.startsWith("-")) {
input = input.replaceFirst("-",""); // or use 'input.substring("1", input.length())';
}
if (input.contains("-") || input.charAt(input.indexOf("/")+1)==('0') || input.contains(" ")) {
valid = false;
} else if (input.contains("/")) {
input = input.replace("/", "");
}
if (input.matches("^[0-9]+$") && input.length() > 0) {
valid = true;
} else {
valid = false;
}
return valid;
}
public static Fraction getFraction() {
System.out.println("Please enter a fraction (a/b) or integer (a): ");
String fracValue = input.nextLine();
//validate input
while (!validFraction(fracValue)) {
System.out.println("Please enter a fraction (a/b) or integer (a): ");
fracValue = input.nextLine();
}
//convert to numerator, denominator
int num = 0;
int den = 0;
if (fracValue.contains("/")) {
num = Integer.parseInt(fracValue.substring(0, fracValue.indexOf("/")));
den = Integer.parseInt(fracValue.substring(fracValue.indexOf("/"), fracValue.length()));
} else {
num = Integer.parseInt(fracValue);
den = 1;
}
// return fraction
Fraction fracConv = new Fraction(num, den);
return fracConv;
}
}
substring(int start, int end) includes the character at start and excludes the character at end. Since the integer cannot be parsed with a / in it, you need to do fracValue.indexOf("/")+1 to get just the numerical part of the denominator.
Firstly you have to understand your input
if your input is String a = "6+7", it means your string length is 3, and alloted indexes are 0,1 and 2
where 0 index is '6', 1 index is '+' and 2 index is '7'
So, when you use a.substring(0, a.indexOf("+")) it means you are saying
a.indexOf("+") = 1 index
you should get a string including '0' index but not 1 index, because substring works with inclusive first param and exclusive second param.
In case of this a.substring(a.indexOf("+")+1, a.length())
you don't want to include '+' in your denominator, So you should not include 1 index, that's why you are adding (+1) with indexof.
So, by adding +1 you are saying only pick value from a.indexOf("+") +1, i.e. 2 index,
and length of string is 3, which means you will get string inclusive of 2 index, i.e 7
if your input is "6 + 7" in that case you should use 'trim()' before using Integer.parseInt.

How do I make my code loop back to the beginning in Java?

I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}

Password Validation (8 letters, 2 numbers, no symbols)

import java.awt.Component;
import javax.swing.JOptionPane;
public class DoSomething {
public static void main(String[] args) {
String password = JOptionPane.showInputDialog(null,
"Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
Component frame = null;
int counter = 0;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
if (password.matches("a-zA-Z")) {
counter++;
character= true;
}
}
if(Character.isLetterOrDigit(c)) {
counter++;
symbol = false;
}
if(Character.isDigit(c)) {
counter++;
if (counter >=2) {
number = true;
}
if (password.length()>=8) {
length = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog("Your Password " +password +" is valid")
}
}
}
Edited -- it still hates length (even if it is 8 or more)
Why not just use regular expressions ?
public static boolean isValid(String password) {
return password.matches("([a-zA-Z]{8,})([0-9]{2,})");
}
This expression (if I'm not mistaken) checks if there are 8 or more characters(lowercase and uppercase) and if there are more than two numbers in the password. Symbols such as $, #, [space] will trigger the expression as false. EDIT: This regular expression only allows a password with 8 (or more) grouped characters and 2 (or more) numbers. Numbers cannot be separated (1MyPassword3) as this will flag the password as invalid. Further investigation will be required.
See the java API for regular expressions:
java 7 Pattern class
java 8 Pattern class
Also check out String.matches(String regex)
Reaction on comment
This code should suit you better then:
int letterCount = 0;
int numberCount = 0;
/*
* Loop through the password and count all the letters and characters
*/
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.toString(c).matches("[a-zA-Z]")) {
letterCount++;
}
if (Character.toString(c).matches("[0-9]")) {
numberCount++;
}
}
if (letterCount > 8) {
// password has 8 or more characters
}
if (numberCount > 2) {
// password has more than 2 numbers
}
Then if you really want to check length as well, you can add this piece of code (outside the for-loop)
if (password.length() >= 10) {
/* Since we need 2 numbers and 8 characters, the password
* can never be valid if it's smaller than 10 characters
*/
else {
/*
* Invalid password
*/
}
Assuming that your conditions for a valid password were:
At least 8 letters
At least 2 numbers
No symbols
At least 10 characters long
String password = JOptionPane.showInputDialog(null, "Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
int letterCounter = 0;
int numCounter = 0;
Component frame = null;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
letterCounter++;
}
else if(Character.isDigit(c)) {
numCounter++;
}
else {
symbol = true;
}
}
//Checking booleans
if (password.length()>=10) {
length = true;
}
if (letterCounter>=8) {
character = true;
}
if (numCounter>=2) {
number = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog(frame, "Your Password " + password + " is valid");
System.out.println("Success");
}
else {
System.out.println("Invalid");
}

How to put a certain character before a certain string?

What I am trying to do is put the # character before the domain. Im also trying to figure out how to put the domains to be the last 4 characters (example .com). How do I go about doing this? Any help would be appreciated.
I have listed my work on this link.
Code from the link:
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
String input = keyboard.nextLine();
while ((input.length() < 8) || (input.length() > 20))
{
System.out.println("Error! Your input is not valid.");
System.out.println("Please try again.");
keyboard.nextLine();
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isUpperCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Error: Try again");
input = keyboard.nextLine();
}
}
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isLowerCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] numbers= {\'0\',\'1\',\'2\',\'3\', \'4\',\'5\',\'6\',\'7\',\'8\',\'9\'};
char[] inputArray = input.toCharArray();
for (int i = 0; i < inputArray.length; i++)
{
for (int j = 0; j < numbers.length; j++)
{
if (inputArray[i]== numbers[j])
{
i=inputArray.length;
j=numbers.length;
}
else
{
if(i == inputArray.length-1 && j== numbers.length-1)
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] SpecialCharacter = {\']\',\'[\',\'?\',\'/\',\'<\',\'~\',\'#\',\'.\',\'!\',\'$\',\'%\',\'^\',\'&\',\'*\',\'(\',\')\',\'+\',\'=\',\'}\',\'|\',\'>\',\'{\' };
char[] inputArray2 = input.toCharArray();
for (int k = 0; k < inputArray2.length; k++)
{
for (int l = 0; l < SpecialCharacter.length; l++)
{
if (inputArray2[k]== SpecialCharacter[l])
{
k=inputArray2.length;
l=SpecialCharacter.length;
}
else
{
if(k == inputArray2.length-1 && l == SpecialCharacter.length-1)
{
System.out.println("No...Try Again");
input = keyboard.nextLine();
}
}
}
String domain1 = ".com";
String domain2 = ".edu";
String domain3 = ".org";
String domain4 = ".mil";
String domain5 = ".gov";
String domain6 = ".net";
}
}
}
}
if you only need to verify that the user has entered a valid email or not then you should use regular expersion for that it makes it more easy and fast.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^(?=.*[0-9]*[a-z]*[A-Z])(?=.*[a-zA-Z])([a-zA-Z0-9]{8,20}+#[A-Za-z0-9]+.(com|org|edu|mil|net))$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* #param hex
* hex for validation
* #return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
hope this will help you. =)
i'll just put this here...
Insert the parts of your code where needed.
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
boolean isOK = false;
String input=new String();
while(!isOK){
input=keyboard.nextLine();
if(input.length() < 20 || input.length() > 8) //length check
{
isOK=true;
}
else
{
isOK=false;
continue;
}
if(input.contains('#')) //check domain
{
isOK=true;
}
else
{
isOK=false;
System.out.println("No # before domain!");
continue;
}
String[] tokens = input.split("#");
String domain=tokens[1];
String username=tokens[0];
//check if contains digit
...
//check uppercase and lowercase in username
...
//check special character in username
...
//split domain
tokens = domain.split(".");
String domainEnding = tokens[1];
//check if the input domain endings are allowed
...
}
}
}
So where the part of input is wrong just use isOK=false;
continue;
BTW: why are you using \' in special character and number arrays?
You could use just '1' , '#' etc.

How to check if a character in a string is a digit or letter

I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

Categories