简体   繁体   English

负整数到字节Java

[英]Negative int to byte Java

My problem is that I can't counting properly length of int, when it's negative. 我的问题是,当它为负数时,我无法正确计算int的长度。

Second problem is that when int number is less than 10 digit if funtion can't ignoring last digit any idea how to fix this issues? 第二个问题是,当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);
}

This is result when I have -1234567890 ten digit: 当我有-1234567890十位数时,这是结果:

Variable length is: 0 digits This is: -1234567890 We have negative variable -1234567890 Last digit (10): 0 Existing result is: 0 变量长度是:0位数字这是:-1234567890我们有负变量-1234567890最后一位数字(10):0现有结果是:0

This is result when I have -123456789 nine digit: 当我有-123456789九位数字时,这是结果:

Variable length is: 0 digits This is: -123456789 We have negative variable -123456789 可变长度为:0位数字,这是:-123456789我们有负变量-123456789

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11 at java.lang.String.substring(String.java:1963) at demo_place.main(demo_place.java:17) 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:java.lang.String.substring(String.java:1963)处为11,demo_place.main(demo_place.java:17)

The index for a String starts from 0 , so when you do; 字符串的索引从0开始,所以当您这样做时;

negative.substring(10, 11) 

the 11th index is out of bounds, since the last char is at index 10 which is '9' , you can just use; 第11个索引超出范围,因为最后一个字符在索引10处为'9' ,您可以使用;

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

to get the last char without hardcoding any index values. 获取最后一个字符而不用硬编码任何索引值。


To get a length of negative integer, just do negative.length() - 1 , to get '-' char out of the picture. 要获得负整数的长度,只需执行negative.length() - 1 ,即可使图片中没有'-'字符。

Or just; 要不就;

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

to get length regardless of whether negative or positive 得到长度,而不管是正数还是负数

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

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