2

I am creating a little trivial palindrome quiz in Java.

I should at some point check if the user will enter more or less than a three digit number such as "1011" or "10" and display an error message such as "Wrong input." However, I can't check the length of a number with int.length() in Java, as I instead could do with a String (String.length()).

How could I solve this problem?

This is my code without the if-three-digit check

import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        System.out.println("Please enter a three digit number number and I will check if it's a palindrome.");

        // create scanner and input number

        Scanner input = new Scanner(System.in);
        int number = input.nextInt();

        int digit1 = (int)(number / 100);
        int remaining = number % 100;
        int digit3 = (int)(remaining % 10);

        System.out.println(number + ((digit1 == digit3) ? " is a palindrome" : " is not a palindrome"));


    }
}
m.rossi
  • 2,602
  • 2
  • 12
  • 13
  • 3
    check if `number < 1000 && number >= 100`. :| besides, you're doing `numberAsString`. you could call length() on this to get the length of the string. – Mridul Kashyap Aug 08 '16 at 07:54
  • sorry Mridul! Forgot to delete that line. Now edited. – m.rossi Aug 08 '16 at 08:05
  • 1
    if the number is int you can use this: `number < 1000 && number >= 100`. but i'd advise against it for a palindrome. why? what if the user enters `010`. for int, it'll be seen as 10 and hence give an error. but as string, it'll be a palidrome. it's up to you to decide which result you wanna show to user, and hence use that method. – Mridul Kashyap Aug 08 '16 at 08:10

3 Answers3

1

You can turn your int to String and use the length function.

Integer.toString(yourNumber).length()
SCouto
  • 7,808
  • 5
  • 32
  • 49
  • 2
    This is a very roundabout and inefficient way when you can just check if the number is greater than 100 and less than 1000, two comparisons, no (hidden) loops. – RealSkeptic Aug 08 '16 at 07:57
  • 1
    I feel very stupid now that I understand I was struggling to write the inefficient and wrong solution to the problem. Thank you all, I knew there was a better way to do this but I didn't noticed. – m.rossi Aug 08 '16 at 08:11
1

Add an if condition once you get the input:

if (number >= 100 && number < 1000) {
   //Proceed with your logic
} else { 
   //Throw you message as invalid number
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46
Dyuti
  • 184
  • 4
1

To check whether a number has certain properties, it is best to use numeric operations, if possible. This usually leads to faster and more straight-forward code.

The smallest number with three digits is 100. The largest number with three digits is 999. So you can test as follows:

if ((number < 100) && (number > 999)) {
  System.out.println("Not a three-digit number :(")
}
Toxaris
  • 7,156
  • 1
  • 21
  • 37