|
I need to write a program that prompts for and accepts a telephone number in the form ddd-ddd-dddd, where d is a digit, and prints it out in the following format: (ddd) ddd-dddd.
thanks =)
|
|
|
import java.io.*;
class EntryTest
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter a number in this format \"ddd-ddd-dddd\"");
boolean acceptable = false;
while(!acceptable)
{
String in = br.readLine();
if(isAcceptable(in))
{
formatString(in);
acceptable = true;
}
else
System.out.println("illegal entry, try again...");
}
br.close();
}
catch(IOException ioe)
{
System.err.println("io: " + ioe.getMessage());
}
}
/**
* there are many ways to do this
*/
private static boolean isAcceptable(String s)
{
String template = "ddd-ddd-dddd";
// check format
int length = s.length();
int firstIndex = s.indexOf("-");
int lastIndex = s.lastIndexOf("-");
if(length != template.length() ||
firstIndex != template.indexOf("-") ||
lastIndex != template.lastIndexOf("-"))
return false;
// check for digits
for(int j = 0; j < length; j++)
{
if(j == firstIndex || j == lastIndex)
continue;
if(!Character.isDigit(s.charAt(j)))
return false;
}
return true;
}
/**
* in: ddd-ddd-dddd
* out: (ddd) ddd-dddd
*/
private static void formatString(String s)
{
String out = "(";
out += s.substring(0, s.indexOf("-"));
out += ") ";
out += s.substring(4);
System.out.println("formatted entry = " + out);
}
}
|
|
|
hello sir/mme,
i'm just new to Java and the code that is written is troubling to read... i just need the basics stuff with no checking and just use simple objects. thank you
|
|
|
class SimpleEntry
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("enter a number in this format " +
"\"ddd-ddd-dddd\" and press Enter");
String in = br.readLine();
String out = "(";
out += in.substring(0, in.indexOf("-"));
out += ") ";
out += in.substring(4);
System.out.println("formatted entry = " + out);
br.close();
}
catch(IOException ioe)
{
System.err.println("io: " + ioe.getMessage());
}
}
}
|
|
|