java如何判断数字的位数?

Python012

java如何判断数字的位数?,第1张

按照num/10 语句,不是应该显示 它是个99位数吗?java是如何判断为3位数的?

答 999/10 = 99        此时num = 99  count=1

    99/10=9           此时num = 9  count=2

    9/10=0            此时num = 0  count=3

    一共在while循环里执行了三次, 所以判断是3位数

提示

System.out.println("它是个"+ count+"位的数!") 

这里输出的是count 这个变量,表达的是次数,

不是输出num 这个数,此时num经过循环已经等于0了

复制以下代码:

int num = 2772

String str = String.valueOf(num)

System.out.println(str.length())

for(char c : str.toCharArray()){

System.out.println(c)

}

扩展资料:

字符串的长度

public class Test {

public static void main(String[] args) {

int count = 0

String regex = "[\u4e00-\u9fa5]"

String str = "今天阳光明媚不是吗."

Pattern p = Pattern.compile(regex)

Matcher m = p.matcher(str)

System.out.print("提取出来的中文有:")

while (m.find()) {

count++

System.out.print(m.group() + " ")

}

System.out.println()

System.out.println("汉字出现的频率:" + count)

}

}

你的getnum方法 定义的时候需要返回int ,但你的方法体里面没有return,报错了

其实这个地方不用返回

            public void getnum(int i) throws AAException {

                if (i < 0 || i > 9999) {

                    throw new AAException()

                }

                if (i >= 0 && i <= 9)

                    System.out.print("一位数")

                else if (i >= 10 && i <= 99)

                    System.out.print("两位数")

                else if (i >= 100 && i <= 999)

                    System.out.print("三位数")

                else if (i >= 1000 && i <= 9999)

                    System.out.print("四位数")

            }

在调用的时候,这样写

        try {

            String s = stdin.nextLine()

            double ii = Double.parseDouble(s)

            int i = (int) ii

            a.getnum(i)

        } catch (AAException e) {

            System.out.println(e.toString())

        }