Question

How would I go about changing an integer like '905 123 7023' into something like '9051237023'.

The assignment is supposed to determine if the phone number inputed is a real phone number.

I was going to use this:

int phoneNumber;
// Code that turns number with spaces into single number
try {
  System.out.println("Please input an integer");
  input = TextIO.getlnInt();
}

catch (InputMismatchException exception) {
  System.out.println("This is not an phone number");
}

To determine the code

Was it helpful?

Solution 2

The data the user is going to enter will be a string (as it could include spaces, and possibly even letters).

There are several ways to remove spaces from a string:

  1. Use split() and join() to split on spaces and join without them
  2. use indexOf() to find spaces, remove them using substring, and iterate until no more spaces
  3. iterate every character of the string, building a new string out of non-space characters
  4. use a regular expression
  5. use replace() (thanks @David Wallace - I completely overlooked the obvious one)

OTHER TIPS

//import java.io.*;
//throws IOException 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int phoneNumber;
try {
    System.out.println("Please input an integer");
    String input = br.readLine();
    phoneNumber=Integer.parseInt(input.replaceAll(" ",""));
}

Start by reading it in as a String if you want to accept phone number input with spaces (or any other hyphens, parenthesis, etc). Then manipulate the string to turn it into something that could represent an long, and parse an long out of it.

But given that it's a phone number and you probably won't be doing any math with it, why not just leave it as a String?

You would have to read the input as a String, verify its in the proper format, and then remove spaces if there are some. Use regular expressions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top