-4

I have homework to check if number is a double digit or a single-digit without using if statement. Thanks for your help!

public class SchoolTest {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int x;
        System.out.println("Please enter a number");
        x = reader.nextInt();
        if ((x > 9 && x < 100) || (x < -9 && x > -100)) {
            System.out.println(true);
            main(args);
        } else {
            System.out.println(false);
            main(args);
        }
    }
}
clcto
  • 9,530
  • 20
  • 42
user3819756
  • 27
  • 1
  • 2
  • 4

5 Answers5

12

Just set the value to the conditional:

boolean isDoubleDigit = (x > 9 && x < 100) || (x < -9 && x > -100);
System.out.println( isDoubleDigit );
clcto
  • 9,530
  • 20
  • 42
3

If the number is known to be non-negative:

int digits = Integer.toString(theIntValue).trim().length();

(trim() probably isn't needed.)

If it might be negative:

int digits = Integer.toString(Math.abs(theIntValue)).trim().length();

If you must return a boolean:

boolean isTwoDigit = Integer.toString(Math.abs(theIntValue)).trim().length() == 2;
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
2
public class Digits {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int check = scan.nextInt();
        //False for single digit, true for double digit
        boolean isDoubleDigit = (check / 10 == 0 && check / 100 == 0) ? false : true;
        System.out.println(isDoubleDigit);
    }
}

Ternary operator is quite helpful in your case

spb1994
  • 114
  • 8
  • 2
    Don't really need the ternary operator either, `bool isDoubleDigit = ! ( check / 10 == 0 && check / 100 == 0 )` – clcto Oct 28 '14 at 22:16
0

You could read the number in as a String rather than an int and use Regex

Gavin
  • 1,725
  • 21
  • 34
-2

Should have been written without the main (args)

  • 2
    Put differently; this is not an answer, and is vague and more likely to lead the asker (and anyone who sees this) off-track rather than actually help. – Ironcache Feb 02 '18 at 17:13