簡體   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