【问题标题】:Java: Check if a number is a double digit or single-digit no if statement? [closed]Java:检查数字是两位数还是一位数 no if 语句? [关闭]
【发布时间】:2014-10-28 20:10:39
【问题描述】:

我有作业要在不使用 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);
        }
    }
}

【问题讨论】:

  • 为什么不想使用 if 语句?
  • 我的老师告诉我们如何不使用if语句
  • 当您发布问题时,最好稍微解释一下您的代码。 :)

标签: java if-statement numbers digits


【解决方案1】:

只需将值设置为条件:

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

【讨论】:

    【解决方案2】:

    如果已知数为非负数:

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

    trim() 可能不需要。)

    如果它可能是负面的:

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

    如果你必须返回一个布尔值:

    boolean isTwoDigit = Integer.toString(Math.abs(theIntValue)).trim().length() == 2;
    

    【讨论】:

      【解决方案3】:
      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);
          }
      }
      

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

      【讨论】:

      • 其实也不需要三元运算符,bool isDoubleDigit = ! ( check / 10 == 0 &amp;&amp; check / 100 == 0 )
      【解决方案4】:

      您可以将数字读取为字符串而不是整数并使用正则表达式

      【讨论】:

      【解决方案5】:

      应该在没有 main (args) 的情况下编写

      【讨论】:

      • 换个说法;这不是答案,而且含糊不清,更有可能导致提问者(以及看到此问题的任何人)偏离轨道,而不是真正提供帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多