infinite loop Get the phone number and test for exit. Check the validity of phon
ID: 3626936 • Letter: I
Question
infinite loopGet the phone number and test for exit.
Check the validity of phone number
if phone number is valid then print it and go back to the loop
otherwise if the phone number is fixable then fix it,print it and go back to the loop
otherwise go back to the loop.
Refinement:
loop
phoneNo=getPhoneNumber()
if(phone isValid(phoneNo))
then
print phoneNo
go back to the loop
else if (isPhoneFixable(phoneNo))
then
phoneNo=Fix the phone(phoneNo)
print phoneNo
go back to loop
else
go back to the loop
end of the loop.
Explanation / Answer
please rate - thanks
import java.util.*;
public class FixPhone
{
public static void main(String args[])
{String phone;
boolean valid;
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
phone=in.nextLine();
while(!phone.equalsIgnoreCase("quit"))
{System.out.print(phone);
if(isValid(phone))
System.out.println(": Valid phone number");
else
{if(canFix(phone))
System.out.println(": Fixed is "+fix(phone));
else
System.out.println(": is not fixable");
}
System.out.print("Enter a phone number: ");
phone=in.nextLine();
}
}
public static boolean isValid(String p)
{int n=0;
char c;
while(n<p.length())
{c=p.charAt(n);
switch(n)
{case 0:if(c!='(')
return false;
break;
case 4:if(c!=')')
return false;
break;
case 8:if(c!='-')
return false;
break;
default: if(!Character.isDigit(c))
return false;
}
n++;
}
return true;
}
public static boolean canFix(String p)
{int n=0,count=0;
while(n<p.length())
{
if(Character.isDigit(p.charAt(n)))
count++;
n++;
}
if(count==10)
return true;
else
return false;
}
public static String fix(String p)
{String result="";
char c;
int n=0,m=0;
while(n<p.length())
{c=p.charAt(n);
if(m==0)
{result=result+'(';
m++;
}
else if(m==4)
{result=result+')';
m++;
}
else if(m==8)
{result=result+'-';
m++;
}
if(Character.isDigit(c))
{result=result+c;
m++;
}
n++;
}
return result;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.