繁体   English   中英

负整数到字节Java

[英]Negative int to byte Java

我的问题是,当它为负数时,我无法正确计算int的长度。

第二个问题是,当int数小于10位时,如果函数不能忽略最后一位,那么如何解决此问题呢?

int number = -123456789;
int length = (int) (Math.log10(number) + 1);
System.out.println("Variable length is: " + length + " digits \nThis is: " + number);

if (number <= -1) {
    System.out.println("We have negative variable");
    String negative = Integer.toString(number);
    System.out.println(negative);

    if (negative.substring(10, 11).isEmpty()||
        negative.substring(10, 11).equals("") ||
        negative.substring(10, 11) == "" ||
        negative.substring(10, 11).equals(null) ||
        negative.substring(10, 11) == null)
    {
        System.out.println("Nothing");
    } else {
        String separate_10 = negative.substring(10, 11);
        System.out.println("Last digit (10): " + separate_10);
        int int_10 = Integer.parseInt(separate_10);
        byte result = (byte) int_10;
    }
    String group = "Existing result is: " + result;
    System.out.println(group);
}

当我有-1234567890十位数时,这是结果:

变量长度是:0位数字这是:-1234567890我们有负变量-1234567890最后一位数字(10):0现有结果是:0

当我有-123456789九位数字时,这是结果:

可变长度为:0位数字,这是:-123456789我们有负变量-123456789

线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:java.lang.String.substring(String.java:1963)处为11,demo_place.main(demo_place.java:17)

字符串的索引从0开始,所以当您这样做时;

negative.substring(10, 11) 

第11个索引超出范围,因为最后一个字符在索引10处为'9' ,您可以使用;

negative.charAt(negative.length() - 1)

获取最后一个字符而不用硬编码任何索引值。


要获得负整数的长度,只需执行negative.length() - 1 ,即可使图片中没有'-'字符。

要不就;

int getIntLength(int integer) {
    String intStr = Integer.toString(integer);
    return intStr.length() + (integer < 0 ? -1 : 0);
}

得到长度,而不管是正数还是负数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM