Question:
help me fix this java code please? how do I put a restriction on string length before I enter the input.?
2014-03-19 16:29:35 UTC
the code I'm working on translates letters into phone numbers, but program must verify that the length of the entered string is exactly 10 or 11. If the length of the string is below 10 or above 11, it should be rejected, and the code displays invalid. how can I put the part where it restricted the length of stringth before the loop, so before I enter any input, the string length must between 10 and 11
Three answers:
daSVgrouch
2014-03-19 18:33:26 UTC
boolean numberIsValid;

System.out.println("Enter a valid 10 or 11 digit phone number");

do {

String phoneNumber = (use a scanner to collect it) ...

numberIsValid = (10 == phoneNumber.length() || 11 == phoneNumber.length() ) ;

if (!numberIsValid) System.out.println("You must enter 10 or 11 digits\nTry again");

while (!numberIsValid);
brilliant_moves
2014-03-19 18:41:41 UTC
Scanner scan = new Scanner(System.in);

String inputString;

do {

System.out.print("Enter phone number (10 or 11 digits): ");

inputString = scan.nextLine();

if (inputString.length() < 10 || inputString.length() > 11) {

System.out.println("Invalid length for inputString");

} // end if

} while (inputString.length() < 10 || inputString.length() > 11);
Deepthroat
2014-03-19 16:34:48 UTC
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;

inputString = inputString.substring(0, maxLength);



try this one


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...