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")); } } 
3
  • 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. Commented Aug 8, 2016 at 7:54
  • sorry Mridul! Forgot to delete that line. Now edited. Commented Aug 8, 2016 at 8: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. Commented Aug 8, 2016 at 8:10

3 Answers 3

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 :(") } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Integer.toString(yourNumber).length() 

2 Comments

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.
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.
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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.