题目描述:
某城市电话号码由三部分组成,分别是:
地区码:空白或者三位数字;
前缀:非0开头的三位数字
后缀:4位数字
假定被测程序能接受一切符合上述规定的电话号码,输出0
拒绝一切不符合规定的电话号码,输出1.
请编写程序实现上述描述的功能.
代码实现:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 某城市电话号码由三部分组成,分别是: 地区码:空白或者三位数字; 前缀:非0开头的三位数字 后缀:4位数字
* 假定被测程序能接受一切符合上述规定的电话号码,输出0 拒绝一切不符合规定的电话号码,输出1. 请编写程序实现上述描述的功能.
*
*/
public class TestCiytNum {
public static void main(String[] args) throws IOException {
String cityCode, prefix, suffix;
// Scanner cin = new Scanner(System.in);
// while(cin.hasNext()){
// cityCode = cin.next();
// prefix = cin.next();
// suffix = cin.next();
// if(null==cityCode||"".equals(cityCode)){
// if (surePrefix(prefix) && sureSuffix(suffix))
// System.out.println(0);
// else
// System.out.println(1);
// }else{
// if (sureCityCode(cityCode) && surePrefix(prefix) && sureSuffix(suffix))
// System.out.println(0);
// else
// System.out.println(1);
// }
// }
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
cityCode=bf.readLine();
prefix=bf.readLine();
suffix=bf.readLine();
if(cityCode.length()==0){
if (surePrefix(prefix) && sureSuffix(suffix))
System.out.println(0);
else
System.out.println(1);
}else{
if (sureCityCode(cityCode) && surePrefix(prefix)&& sureSuffix(suffix))
System.out.println(0);
else
System.out.println(1);
}
}
private static boolean sureCityCode(String cityCode) {
if(null==cityCode||"".equals(cityCode))
return false;
if (cityCode.length() != 3) {
return false;
} else if(cityCode.length() ==3){
for (int i = 0; i < 3; i++) {
if (cityCode.charAt(i) < 48 || cityCode.charAt(i) > 57)
return false;
}
}
return true;
}
private static boolean surePrefix(String prefix) {
if(null==prefix||"".equals(prefix))
return false;
if(prefix.length()!=3)
return false;
else{
if(prefix.charAt(0)==48)
return false;
else{
for (int i = 0; i < 3; i++) {
if (prefix.charAt(i) < 48 || prefix.charAt(i) > 57)
return false;
}
}
}
return true;
}
private static boolean sureSuffix(String suffix) {
if(null==suffix||"".equals(suffix))
return false;
if(suffix.length()!=4){
return false;
}else{
for (int i = 0; i < 4; i++) {
if(suffix.charAt(i)<48||suffix.charAt(i)>57)
return false;
}
}
return true;
}
}
经测试所有用例全部通过,如有错误请指正