Ritu Raj Shrivastava
Ritu Raj Shrivastava

Reputation: 79

Whаt is happening here?

Rules for valid Indian mobile number:

The number should contain 10 or 11 or 12 digits.

If it contains 10 digits, then the first digit should be 7 or 8 or 9.

If it contains 11 digits, then the first digit should be 0 and the second rule followed.

If it contains 12 digits, then the first two digits should be 91 and the second rule followed.

For test case:

1
881906355596

this code should produce Invalid but it is showing Valid.

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
    public static void main (String[] args)
     {
     Scanner scan = new Scanner(System.in);
     int t=scan.nextInt();
     while((t--)!=0){

         String s = scan.next();
         int length = s.length();

         if((length==10) &&((s.charAt(0)=='7')||(s.charAt(0)=='9')||(s.charAt(0)=='8')))
         System.out.println("Valid");

         else if((length==11) &&(s.charAt(0)=='0')&&(s.charAt(0)=='7')||(s.charAt(0)=='9')||(s.charAt(0)=='8'))
         System.out.println("Valid");//code

         else if((length==12) &&(s.charAt(0)=='9')&&(s.charAt(1)=='1'))
         System.out.println("Valid");//code

         else System.out.println("Invalid");
     }
     }
}

Upvotes: 0

Views: 132

Answers (2)

Eran
Eran

Reputation: 393771

Your second and third conditions are wrong.

The second condition incorrectly returns true for your 881906355596 input.

You'll see why if you arrange it as follows:

else if (
    (length==11) &&           // false &&
    (s.charAt(0)=='0') &&     // false &&
    (s.charAt(0)=='7') ||     // false ||
    (s.charAt(0)=='9') ||     // false || 
    (s.charAt(0)=='8')        // true 
)                             // equals true

It should be:

else if (length == 11 && s.charAt(0) == '0' && (s.charAt(1) == '7' || s.charAt(1) == '9' || s.charAt(1) == '8'))

The third condition should be:

else if (length == 12 && s.charAt(0) == '9' && s.charAt(1) == '1' && (s.charAt(2) == '7' || s.charAt(2) == '9' || s.charAt(2) == '8'))

Upvotes: 6

dguy
dguy

Reputation: 140

You missed one whole ()

else if((length==12) &&((s.charAt(0)=='9')&&(s.charAt(1)=='1')))

Upvotes: -3

Related Questions