Java:检查一个数字是两位数还是一位数没有if语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26617573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:56:59  来源:igfitidea点击:

Java: Check if a number is a double digit or single-digit no if statement?

javaif-statementnumbersdigits

提问by user3819756

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

我有作业要在不使用 if 语句的情况下检查数字是两位数还是一位数。谢谢你的帮助!

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);
        }
    }
}

回答by Gavin

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

您可以将数字作为 String 而不是 int 读入并使用 Regex

回答by clcto

Just set the value to the conditional:

只需将值设置为条件:

boolean isDoubleDigit = (x > 9 && x < 100) || (x < -9 && x > -100);
System.out.println( isDoubleDigit );

回答by spb1994

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

三元运算符对您的情况非常有帮助

回答by Hot Licks

If the number is known to be non-negative:

如果已知数字为非负数:

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

(trim()probably isn't needed.)

trim()可能不需要。)

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;

回答by Shane parker

Should have been written without the main (args)

应该在没有主要(参数)的情况下编写