Ace Ace - 6 months ago 8
Java Question

Length of string not considering zeros in the start

I am trying the following question. I need to find the length of integer digit so I converted it into string and I am able to get output for all the numbers except the numbers starting with zeros. I am only able pass 1 testcase out of three. I am not able to figure out what else is wrong in my code.

Code:

import java.util.*;

class Test {

public static void main(String []args) {
int no;
int sum;

Scanner sc=new Scanner(System.in);
no = sc.nextInt();

String x=Integer.toString(no);

int len=x.length();

int lno=no%10; //3rd digit
int fno=no; //first digit
int mno=(no/10)%10; //middle digit

while(fno>=10) {
fno/=10;
}

sum=fno+lno;

if(len!=3) {
System.out.print("Invalid Input\n");

} else {
if(sum==mno) {
System.out.print("Lucky Number\n");

} else {
System.out.print("Not A Lucky Number\n");
}
}
}


}

Answer

Why don't you use the next(Pattern) method available in Scanner?

You can then use a regex to match a 3-digit number and if it doesn't match it will throw a InputMismatchException which you can catch and output Invalid Input.

If it does match then you know you have a String of length 3 which you can then use each char as an individual number. Add the first and last index together and see if it equals the second index.

public static void main(String[] args) throws IOException {

    try (Scanner scan = new Scanner(System.in)) {

        try {
            String number = scan.next(Pattern.compile("\\d{3}"));

            int i = Integer.parseInt("" + number.charAt(0));
            int j = Integer.parseInt("" + number.charAt(1));
            int k = Integer.parseInt("" + number.charAt(2));

            if ((i + k) == j) {
                System.out.println("Lucky Number");
            } else {
                System.out.println("Not A Lucky Number");
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid Input");
        }
    }
}