Numbers with embedded dashes play a huge role in our lives. Think of your phone
ID: 3784679 • Letter: N
Question
Numbers with embedded dashes play a huge role in our lives. Think of your phone number, or Social Security number. Write a program that uses a Scanner to take a single user input. You may assume this input contains no spaces, and consists of any number of digits with two dashes. Use only String's indexOf lastndexOf and substring methods. Sample input might be 123-45-6789 Or 919-555-1212 Your program should remove the dashes and print the digits. The output for the above input would be 123456789 and 9195551212Explanation / Answer
PROGRAM CODE:
package simple;
import java.util.Scanner;
public class RemoveNumber {
public static void main(String[] args) {
String number;
System.out.print("Enter a number: ");
//Scanner object to read from console
Scanner consoleReader = new Scanner(System.in);
number = consoleReader.nextLine();
// continuing to remove dashes till a dash('-') is found in the string. -1 means that dash is not found
while(number.lastIndexOf("-") != -1)
{
int index = number.lastIndexOf("-");
number = number.substring(0, index) + number.substring(index+1, number.length());
}
System.out.println("Number after removing dashes: " + number);
consoleReader.close();
}
}
OUTPUT:
Enter a number: 123-456-789
Number after removing dashes: 123456789
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.