How can I validate a phone number input of several variations? - java

My program currently validates the phone number only when it is ten consecutive numbers and characters and it closes when the word "exit" is typed. However, I was wondering how I could validate the numbers if they were also written as both, for example, (123)456-7890 and 123-456-7890
import java.util.Scanner;
public class Q2
{
public static void main(String[] args){
Scanner kb=new Scanner(System.in);
while (true){
System.out.print("Enter your phone number: ");
String number=kb.next();
if(number.equals("exit")){
System.exit(0);
}
boolean valid=true;
for(int i=0;i<number.length();i++){
if(number.length()!=10) valid=false;
}
if (valid) System.out.println("It is valid");
else System.out.println("It is invalid");
}
}
}

You do that by doing real validation.
Meaning: "validation" describes the process of checking your input against a set of rules. If the input conforms to all those rules, it is valid; otherwise it is not.
So, yes, checking the length was a first simple rule; but "length is 10" ... just turns out to not be a good rule. For example, "123456A90" has length 10; but is invalid.
What you can do instead (just giving you some ideas):
use regular expressions (or plain string parsing) in order to determine if your input string matches a certain pattern, like (nnn-nnnn-nnnn)
simple replace all "unwanted" characters, such as ( ) - with ""; and then you check if the resulting string has length 10.
So, the answer is: have a close look at your input and determine the properties that valid phone numbers have in common. And then you start writing code to check those.

Why you simply don't use regex like this its more powerful :
public static void main(String[] args) {
System.out.println("123-456-7890 is valid? " + valider("123-456-7890"));
System.out.println("(123)456-7890 is valid? " + valider("(123)456-7890"));
}
private static boolean valider(String phoneNumber) {
if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
return true;
} else return phoneNumber.matches("\\(\\d{3}\\)\\d{3}-\\d{4}");
}

Related

What's a better or more standard way to perform this function?

I am a java beginner, and in this particular problem I practiced making a program that converts any given string to lowercase string. Is there a a better way to achieve this goal in java (in terms of design)?
Also, how does the "else" (after "else if") catches or waits for me to make an input. Somehow that part does not make sense to me, even though I achieved what I wanted. How is the value of "ans" from input transferred to the entire loop and used until the loop is closed?
After many attempts and failures, I used a separate method for the conversion part. My second question is a bit too complicated to be researched.
import static java.lang.System.out;
import java.util.Scanner;
public class MyClass {
public static Scanner s = new Scanner(System.in);
public static String ans;
public static void main(String args[]) {
Conversion();
do {
ans = new String(s.nextLine());
if (ans.equalsIgnoreCase("Y")) {
Conversion();
} else if (ans.equalsIgnoreCase("N")) {
out.println("Thank you for using this program!");
break;
} else {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
} while (ans != "N");
}//END MAIN
public static void Conversion() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
out.println("Your new string is: " + str.toLowerCase());
out.println("Would you like to convert another string? (Y/N)");
}
}
I notice a few issues; Conversion looks like a class-name (Java naming convention would be conversion) and ans != "N" is using == instead of .equals - and wouldn't ignore case (!ans.equalsIgnoreCase("N")). Globals (e.g. static) are bad (pass the Scanner to the methods that need it), and the static import just makes the code more difficult to reason about (in my opinion). Your current loop doesn't really follow a conventional form, I would extract the prompt and loop for "another" conversion to a new method and if you must print a thank you I'd do so after the "main loop". Something like,
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
do {
conversion(sc);
} while (another(sc));
System.out.println("Thank you for using this program!");
}
public static void conversion(Scanner s) {
System.out.println("Please enter string to be converted to lowercase: ");
System.out.printf("Your new string is: %s%n", s.nextLine().toLowerCase());
}
public static boolean another(Scanner s) {
while (true) {
System.out.println("Would you like to convert another string? (Y/N)");
String ans = s.nextLine();
if (ans.equalsIgnoreCase("Y")) {
return true;
} else if (ans.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Invalid entry!");
System.out.println("(Please type 'Y' for yes, or 'N' for no.)");
}
}
Answering your first question:
There are many design patterns and practices so many people can argue what I would recommend you to do. It's basically the same for all programming languages. Let's take your function "Conversion". The name itself says that you use it to convert stuff. Not to display, not to prompt - to convert. In this case, the only actual thing it should do is to convert upperCase to lowercase. In fact, you might want to specify what type of conversion it has in the name of the function (convertToLowerCase?). In fact, in Java, we use lowerCamelCase for all function names and UpperCamelCase for classes.
If you accept my previous suggestion, you could break the Conversion function into multiple ones like promptUserForInput, WrongInputHandler and so forth.
If I understood your second question correctly, you wonder about the way the code executed and how the variable ans is transferred further into the loop. Let's take a look at your code and what variables do:
You initialize your variable in the class MyClass by making it accessible to all methods in the class;
You prompt the user for the input to assign to this variable inside the do..while loop with this line ans = new String(s.nextLine()); which saves the value of the variable and, again, which can be accessed inside the whole class so its value is changed.
It goes into the if..else if...else statement. The way it works, it goes line by line - if the first if-statement fails, it goes on until it finds a truthy statement and it doesn't go any further. In your case, if the ans is not equal to either y/Y/ it will go to else if statement and if it's not n/N, it will go to else (so basically whatever except y/Y/n/N) and will be executed. After that, it jumps into the while (ans!= "N"); line where it compares your class-member variable ans and if it's not equal to "N" it starts over the loop right after the do{ part until you type in the "N".
I hope that makes sense. Whenever the program is asking you for input, it does not execute code further but is stuck until you provide any input. The value from input itself isn't passed throughout the loop and the program. The reason why you can use it because you created a higher-scope variable ans where you saved the result of your input.
IMPORTANT: if you've declared the ans inside the do..while loop, you would've not been able to have accessed it in the while (ans...) because it will 'die' right before the curly brace between do { ...here} while(). If you want to learn more about the scope and variables in general, you can read this article.
Here is my code example:
public static void main(String args[]) {
//declare before entering the loop to have higher scope
String ans = "y";
do {
//we get the given string to convert from the user
String str = promptForString();
//we convert the string
str = converseStringToLowerCase(str);
//display the string (could use another function for that: easier to debug and locate problems and in bigger projects)
out.println("Your new string is: " + str);
//prompt user for respond to continue or not
ans = promptForContinue();
handleResponse(ans);
} while (!ans.equals("n"));
}//END MAIN
//prompts user for an input string
public static String promptForString() {
out.println("Please enter string to be converted to lowercase: ");
String str = new String(s.nextLine());
return str;
}
//converts any given string to lower case
public static String converseStringToLowerCase(String str) {
return str.toLowerCase();
}
//is used to prompt user for reply
public static String promptForContinue() {
out.println("Would you like to convert another string? (Y/N)");
String str = new String(s.nextLine());
//is good to make if...else statements easier - it will always be lower case (or upper if you prefer)
return str.toLowerCase();
}
//easier to locate other response scenarios
public static void handleResponse(String response) {
if (response.equals("n")) {
out.println("Thank you for using this program!");
//it's not a very good practice to innaturally break loops. Use input for that in while(..) statement
// break;
} else if (!response.equals("y")) {
out.println("Invalid entry!");
out.println("Would you like to convert another string?\n(Please type 'Y' for yes, or 'N' for no.)");
}
}

Is it possible to set an exact number of characters for an input using StringBuilder?

I'd like to be able to force a 10 character input using StringBuilder. I know it can be set to a max char limit but can I make it exactly 10?
Maybe something like this:
import java.util.Scanner;
public class Phonenumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
StringBuilder num = new StringBuilder(System.in);
System.out.println("What is your 10 digit phone number?");
num = input.nextStringBuilder();
while(!(num =(10 characters)) // I don't know how to phrase this.
{
System.out.println("Sorry, you entered the wrong ammount of digits");
}
if(num =(10 characters)
{
System.out.println("Your Phone number is " + num);
}
}
}
Best alternate is to use String instead of StringBuilder and use String.length() method to validate input from user and your code also needs some correction..
import java.util.Scanner;
public class Phonenumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//StringBuilder num = new StringBuilder(System.in); As we are using String,StringBUilder is not needed
System.out.println("What is your 10 digit phone number?");
String num = input.nextLine();
if(!(num.length()==10)) // Correction: If you use while here and user enters input not having 10 digits it will go to endless loop
{
System.out.println("Sorry, you entered the wrong ammount of digits");
}
if(num.length()==10) //Here you can use else to make your code more appropriate in case of time complexity(Here Time complexity won't matter but as you seem to be new to java, I think you should check this property)
{
System.out.println("Your Phone number is " + num);
}
}
}
Try this:
System.out.println("What is your 10 digit phone number?");
String num = input.nextLine();
while (!num.matches("\\d{10}")) {
System.out.println("Sorry, you did not enter exactly 10 digits. Try again");
num = input.nextLine();
}
This checks that the length is exactly 10 and that all characters are digits.
But you could go one step better and remove non-digits in case the user entered formatting characters (like brackets, dashed and spaces), yet still accept the input, by changing the reads to:
input.nextLine().replaceAll("\\D", "");
FYI \D means "non digit". This kind of input cleansing is what every input field should have in the real world, but all to often does not.
<input type="text" id ="idOfValueToTest" />
<input type="submit" id ="btnValidate" value="Submit" onclick="return Validate()" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<script type="text/javascript">
function Validate() {
var validation = document.getElementById("idOfValueToTest").value;
var pattern = /^\d{10}$/;
if (pattern.test(validation)) {
return true;
}
return false;
}
</script>
Try this!
I'm sorry i misread java to javascript. The regex should work though. Try:
public static boolean isValid(String input)
{
String regex = "^\d{10}$";
if(input.matches(regex))
{
return true;
}
return false;
}
Hi, i see what you're saying. Well as other have said you should not use stringbuilder to do that. If you're looking for resources then i would suggest reading the class description here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html . Basically as the name says, a stringbuilder builds strings! It might be a weird way to actually do what you want using append but that would be really weird and really bad programming. I will add an example of what you should NOT do!
String text = "abcdefghijklmnopq";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++)
{
builder.append(Character.toString(text.charAt(i)));
}
String result = builder.toString();
System.out.println(result);
See what other people posted if you're looking a most commonly used way to do this. If regex seems complicates then i would suggest going with .length as that is pretty straight forward, but do some research on regex, is a very good tool!
My main problem was that I was trying to have user input and limit it to 10 characters. I recently found out that it is impossible to fill a StringBuilder from user input. I can amend it once it's been converted to a string but I can't use String Builder to directly limit it.

Determine if input string matches clock time using regular expressions in Java

I'm trying to determine if an input string is in a valid 24-hour date format (ie. hh:mm:ss). I'm using a few different logics and have been mostly successful with my test cases. My code currently fails for all the inputs I've tried (including the ones below).
The expression is supposed to work in the following way:
Inputting 11:24:10 should output Valid form
inputting 00:13:42 should output Valid form
Inputting 24:52:25 should output Invalid form
Inputting 05:62:55 should output Invalid form
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
String input = new Scanner(System.in).nextLine();
if (input.matches("((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
}
}
I've only recently started learning Java and I apologize if this question has been asked before (I googled!). Thanks for your help!
It should be
(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]
According to your regex
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
It will match ((0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]
You can also use non capturing group if you just want to match it as
(?:(?:(?:0|1)[0-9])|(?:2[0-3])):[0-5][0-9]:[0-5][0-9]
Your regex can be simplified further as by modifying hours part
[01][0-9]
IDEONE DEMO
EDIT
Little bit modification
(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
REGEX DEMO
The issue is that your current regex will match (0|1)[0-9]) or (2[0-3]):[0-5][0-9]:[0-5][0-9]. You want your || operator to work on the (0|1)[0-9]) and (2[0-3]). So what you want is this:
((0|1)[0-9])|(2[0-3]):[0-5][0-9]:[0-5][0-9]
You also have a resource leak because you do not close your Scanner. It is best to store the new Scanner in a variable so that you can close it later. Here is the full code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("String to check: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.matches("(((0|1)[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]")) {
System.out.println("Valid form");
} else {
System.out.println("Invalid form");
}
sc.close();
}
}

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Need help splitting a string into two separate integers for processing

I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split

Categories

Resources