Validating 7 digit phone number - java

What I'm trying to accomplish is the following...
Asks user for number and check to see if number provided by user input is a 7 digit integer.
If it's a string, throw InputMismatchException and ask again for the number. Is there an easy way to accomplish this other than using regex and provided that the number is in the form 1234567? The other problem is if I input a value such as 12345678, it gets rounded due to int, so how do avoid this.
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}

A valid telephone number is not necessarily an integer (Containing a + sign for country codes for example). So use a String instead.
Simple example with basic regex (7 digits, not validating country codes etc.):
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}

Here is working example along the lines of your original idea.
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}

Related

Non duplicates numbers in user input

I am trying to work out how to create an input validation where it won't let you enter the same number twice as well as being inside a range of numbers and that nothing can be entered unless it's an integer. I am currently creating a lottery program and I am unsure how to do this. Any help would be much appreciated. My number range validation works but the other two validations do not. I attempted the non duplicate number validation and i'm unsure how to do the numbers only validation. Can someone show me how to structure this please.
This method is in my Player class
public void choose() {
int temp = 0;
for (int i = 0; i<6; i++) {
System.out.println("Enter enter a number between 1 & 59");
temp = keyboard.nextInt();
keyboard.nextLine();
while ((temp<1) || (temp>59)) {
System.out.println("You entered an invalid number, please enter a number between 1 and 59");
temp = keyboard.nextInt();
keyboard.nextLine();
}
if (i > 0) {
while(temp == numbers[i-1]) {
System.out.println("Please enter a different number as you have already entered this");
temp = keyboard.nextInt();
keyboard.nextLine();
}
}
numbers[i] = temp;
}
}
Do it as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int[] numbers = new int[6];
static Scanner keyboard = new Scanner(System.in);
public static void main(String args[]) {
// Test
choose();
System.out.println(Arrays.toString(numbers));
}
static void choose() {
int temp;
boolean valid;
for (int i = 0; i < 6; i++) {
// Check if the integer is in the range of 1 to 59
do {
valid = true;
System.out.print("Enter in an integer (from 1 to 59): ");
temp = keyboard.nextInt();
if (temp < 1 || temp > 59) {
System.out.println("Error: Invalid integer.");
valid = false;
}
for (int j = 0; j < i; j++) {
if (numbers[j] == temp) {
System.out.println("Please enter a different number as you have already entered this");
valid = false;
break;
}
}
numbers[i] = temp;
} while (!valid); // Loop back if the integer is not in the range of 1 to 100
}
}
}
A sample run:
Enter in an integer (from 1 to 59): 100
Error: Invalid integer.
Enter in an integer (from 1 to 59): -1
Error: Invalid integer.
Enter in an integer (from 1 to 59): 20
Enter in an integer (from 1 to 59): 0
Error: Invalid integer.
Enter in an integer (from 1 to 59): 4
Enter in an integer (from 1 to 59): 5
Enter in an integer (from 1 to 59): 20
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 25
Enter in an integer (from 1 to 59): 6
Enter in an integer (from 1 to 59): 23
[20, 4, 5, 25, 6, 23]
For testing a value is present in the numbers array use Arrays.asList(numbers).contains(temp)
May better if you use an ArrayList for storing numbers.
I would rewrite the method recursively to avoid multiple loops.
If you are not familiar with recursively methods it is basically a method that calls itself inside the method. By using clever parameters you can use a recursively method as a loop. For example
void loop(int index) {
if(index == 10) {
return; //End loop
}
System.out.println(index);
loop(index++);
}
by calling loop(1) the numbers 1 to 9 will be printed.
In your case the recursively method could look something like
public void choose(int nbrOfchoices, List<Integer> taken) {
if(nbrOfChoices < 0) {
return; //Terminate the recursively loop
}
System.out.println("Enter enter a number between 1 and 59");
try {
int temp = keyboard.nextInt(); //Scanner.nextInt throws InputMismatchException if the next token does not matches the Integer regular expression
} catch(InputMismatchException e) {
System.out.println("You need to enter an integer");
choose(nbrOfChoices, taken);
return;
}
if (value < 1 || value >= 59) { //Number not in interval
System.out.println("The number " + temp + " is not between 1 and 59.");
choose(nbrOfChoices, taken);
return;
}
if (taken.contains(temp)) { //Number already taken
System.out.println("The number " + temp + " has already been entered.");
choose(nbrOfChoices, taken);
return;
}
taken.add(temp);
choose(nbrOfChoices--, taken);
}
Now you start the recursively method by calling choose(yourNumberOfchoices, yourArrayList taken). You can also easily add two additonal parameters if you want to be able to change your number interval.
What you want to do is use recursion so you can ask them to provide input again. You can define choices instead of 6. You can define maxExclusive instead 59 (60 in this case). You can keep track of chosen as a Set of Integer values since Sets can only contain unique non-null values. At the end of each choose call we call choose again with 1 less choice remaining instead of a for loop. At the start of each method call, we check if choices is < 0, if so, we prevent execution.
public void choose(Scanner keyboard, int choices, int maxExclusive, Set<Integer> chosen) {
if (choices <= 0) {
return;
}
System.out.println("Enter enter a number between 1 & " + (maxExclusive - 1));
int value = keyboard.nextInt();
keyboard.nextLine();
if (value < 1 || value >= maxExclusive) {
System.out.println("You entered an invalid number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
if (chosen.contains(value)) {
System.out.println("You already entered this number.");
choose(keyboard, choices, maxExclusive, chosen);
return;
}
chosen.add(value);
choose(keyboard, --choices, maxExclusive, chosen);
}
choose(new Scanner(System.in), 6, 60, new HashSet<>());
I hope it will help , upvote if yes
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private ArrayList<String> choose() {
Scanner scanner = new Scanner(System.in);
ArrayList<String> alreadyEntered = new ArrayList<>(6); // using six because your loop indicated me that you're taking six digits
for(int i = 0 ; i < 6 ; ++i){ // ++i is more efficient than i++
System.out.println("Enter a number between 1 & 59");
String digit;
digit = scanner.nextLine().trim();
if(digit.matches("[1-5][0-9]|[0-9]" && !alreadyEntered.contains(digit))// it checks if it is a number as well as if it is in range as well if it is not already entered, to understand this learn about regular expressions
alreadyEntered.add(digit);
else {
System.out.println("Invalid input, try again");
--i;
}
}
return alreadyEntered // return or do whatever with the numbers as i am using return type in method definition i am returning
}
scanner.close();
}
using arraylist of string just to make things easy otherwise i would have to to some parsing from integer to string and string to integer

Why does Java outputs decimal number as Integer?

So here is my program:
// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("How old are you? ");
int age = checkValidAge();
if (age != 0)
{
System.out.println("You are " + age + " years old");
}
}
public static int checkValidAge()
{
try
{
return userInput.nextInt(); // nextInt() receives the user input
}
catch (InputMismatchException e)
{
userInput.next(); // Skips the last user input and waits for the next
System.out.print("That isn't a whole number");
return 0;
}
}
When I enter a number with 3 decimal places, Java outputs it as an Integer:
If I input the number with 2 or more than 3 decimal points, then the program will know that input is not correct. So why does it ignore 3 decimal places and outputs it as an int?
Stream::nextInt reads an integer from a stream.
2,444 is an integer in your default locale (2,444 = 2444).
If you want to read a decimal number you need to use the Stream::nextDouble or another appropriate method.

Testing if an input is Integer and larger than (two conditions) with do-while loop - Java

I need input from a user to be integer and larger than 10.
Here is my code.
import java.util.*; //program uses class Scanner
public class Tests {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an Integer");
int weight;
do {
while (!input.hasNextInt()) {
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
System.out.println("Enter an Integer >= 10");
weight = input.nextInt();
} while (weight < 10);
System.out.println("OK");
}
}
My expected output will be to if the weight is integer to print "OK".
But my actual output is
Enter an Integer
20
Enter an Integer >= 10
OK
I cannot figure out how to get rid of the "Enter an Integer >= 10" when conditions satisfied.
Only print the message if the input does not satisfy the condition.
do {
while (!input.hasNextInt()) {
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
weight = input.nextInt();
if ( weight < 10 ) {
System.out.println("Enter an Integer >= 10");
}
} while (weight < 10);
Use a single while loop that checks a single input at a time. Once you get any input you first verify that it's an integer, the .matches(\d+), if it does match an integer check if the integer is greater than 10, if it's not then ask for an Integer. If all the checks pass then the last else means we got a valid entry from the user.
Scanner input = new Scanner(System.in);
int weight = -1;
String userInput = "";
System.out.println("Enter an Integer: ");
while(weight < 10)
{
userInput = input.nextLine();
//check if it's not a digit
if(!userInput.matches("\\d+"))
{
System.out.println("Enter an Integer: ");
}
//check if the integer we got is less than 10
else if(Integer.parseInt(userInput) < 10)
{
System.out.println("Enter a Number > 10:");
}
//we get here when all conditions are satisfied
else
{
weight = Integer.parseInt(userInput);
}
}
System.out.println("OK");
Output
Enter an Integer:
gf
Enter an Integer:
ytu76
Enter an Integer:
1
Enter a Number > 10:
20
OK
Pavel. Although your question title mentions using a "do-while" loop, the question didn't specify if that's a hard requirement for some reason. I would opt for something like this, without using a do-while:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an Integer");
int weight;
while ((weight = readInteger(input)) < 10) {
System.out.println("Enter an Integer >= 10");
}
System.out.println("OK");
// do something with weight value
}
private static int readInteger(Scanner input) {
while (!input.hasNextInt()) {
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
return input.nextInt();
}
Though the answers do suggest the ways to resolve following the algorithm you're looking for and it could be solved with -
do {
System.out.println("Enter an Integer >= 10");
weight = input.nextInt();
} while (weight < 10);
Yet another interesting point that drew my attention to your code was, how should the following be processed
while (!input.hasNextInt()) { // this block is never reached actually
System.out.println("Please enter an integer!");
input.next(); // this is important!
}
and why did the compiler wait for an input without either printing Enter an Integer >= 10 or Please enter an integer!. And found out that's because your method call hasNextInt() awaits your input but would eventually process the next statement once you've provided some integer input (irrespective)(tried 10 and 10 10 as input as well.) The reason being the radix that is getting passed in the input provided would remain default.
Bringing this all out from the Scanner.java in the java.util
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the default radix using the
* {#link #nextInt} method. The scanner does not advance past any input.
*
* #return true if and only if this scanner's next token is a valid
* int value
* #throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}
JavaDoc for hasNextInt() which in turns calls the overloaded method -
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {#link #nextInt} method. The scanner does not advance past any input.
*
* #param radix the radix used to interpret the token as an int value
* #return true if and only if this scanner's next token is a valid
* int value
* #throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt(int radix) {
setRadix(radix);
JavaDoc for hasNextInt(int radix) which calls the setRadix method.
// The next operation should occur in the specified radix but
// the default is left untouched.
private void setRadix(int radix) {
Couldn't possibly find this in the JavaDoc though.

Reversing digits in Java. Leading and trailing zeros won't print

The problem was to reverse user entered digits. I have it working but while testing it I realized that it won't print either leading or trailing zeros.
For example if I enter 10 it only displays 1 in the result.
If I enter 0110 I get a result of 11.
Here is my code:
public class ReversingDigits {
int value;
int reverse;
public ReversingDigits() {
value = 10;
reverse = 0;
}// end constructor
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
value = input.nextInt();
if (value < 10 || value > 9999){
System.out.print("Please enter a valid 2-4 digit number: ");
value = input.nextInt();
}
while (value > 0) {
reverse *= 10;
reverse += value % 10;
value /= 10;
}
System.out.println("Reversed numbers are: " + reverse);
}
}//end class
Any ideas on how to get the zeros to print?
Thanks
Make sure you work with a String while reversing your number. It will preserve leading zeros. As you know 00001 is the same as 1 when in int representation, and so converting that to a string will remove all leading zeros.
Here's your code sample modified to read a string from the input, and only convert it to an int when you need to check the range.
public void reverse() {
System.out.println("Enter a valid 2-4 digit number: ");
Scanner input = new Scanner(System.in);
String value = input.next();
int valueInt = Integer.parseInt(value);
if (valueInt < 10 || valueInt > 9999){
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
}
String valueReversed = new StringBuilder(value).reverse().toString();
System.out.println("Reversed numbers are: " + valueReversed);
}
Note that in your code, if a user enters the wrong range twice in a row, your program won't prompt him again. You may want to put this part of the code into a do-while loop which only exits when the input range is correct. Example
do {
System.out.print("Please enter a valid 2-4 digit number: ")
value = input.next();
int valueInt = Integer.parseInt(value);
} while (valueInt < 10 || valueInt > 9999);
//only get here when inputted value finally within target range.
Edit: As mentioned by #Levenal, you may also want to wrap Integer.parseInt in a try/catch block for NumberFormatException in the event the user passes in a non-numerical input.
As has been pointed out, reversing numbers you are much better off reversing a string. If you are allowed to stray away from console input, JOptionPane is quite good for simple String input, like so:
while(true){
String input = JOptionPane.showInputDialog("Please anter a number between 10 & 9999: ");
if(input == null){//If input cancelled
break; //Exit loop
} else if(input.matches("\\d{2,4}")){//Regex for at least 2 but no more than 4 numbers
System.out.println(new StringBuilder(input).reverse().toString());//Reverse
break;
}
}
Good luck!

How do I validate the less then zero inputs efficiantly without so many of the same else statements?

I am trying to create a computer simulation of money losses over blackjack games. However I am running into a bug where if I put a less then zero value in one of the prompts, the program has to go through all the other prompts before warning about the less then zero.
Is there a way to immediately warn about less then zero values without having to put the same exact else statement for each if over and over again?
private void menu()
{
boolean NonNumeric=false;
//This is so a different exception is thrown for the minimum stakes since it's a float.
boolean isDecimal=false;
while(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0 )
{
try
{
Scanner input = new Scanner(System.in);
if(getRounds()<=0)
{
System.out.println("Enter number of rounds.");
setRounds(input.nextInt());
}
if(getPlayers()<=0)
{
System.out.println("Enter number of players.");
setPlayers(input.nextInt());
}
if(getStakes()<=0)
{
System.out.println("Enter minimum stakes.(Note: All players bet minimum only)");
isDecimal=true;
setStakes(input.nextFloat());
}
}
catch (InputMismatchException e ) //In case some idiot enters a letter or symbol.
{
//This if statement is so that a different message comes if the invalid entry is a float.
if(isDecimal==true)
{
System.out.println("Entry must be a number. Not a letter or symbol. Try Again.\n");
}
else
{
System.out.println("Entry must be a whole number. Not a letter, decimal, or symbol. Try Again.\n");
}
/*This boolean is so that the below if statement does not run if the user enters a letter
since the integer defaults back to a 0 on exception.*/
NonNumeric = true;
}
if(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0)
{
System.out.println("Number must be greater than 0.\n");
}
}
}
Modularize. Create a method (or even a class) that takes an input and accepts it only if it meets conditions. For example
private int myIntGetter(String caption, boolean forcePositive) {
System.out.println(caption);
Scanner input = new Scanner(System.in);
int intValue = input.nextInt();
while ((forcePositive) && (intValue <=0)) {
System.out.println("Number must be greater than \0");
System.out.println(caption);
intValue = input.nextInt();
}
// here intValue is valid
return intValue;
}
If you're not to concerned with being nice to your user:
do{
System.out.println("Enter number of rounds. Rounds must greater than zero.");
setRounds(input.nextInt());
}while( getRounds()<=0);
You can do that for each thing the user has to enter. It's quick and dirty.

Categories