我的問題是當它是負數時,我無法正確計算 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線程“main”中的異常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍:11 at java.lang.String.substring(String.java:1963) at demo_place.main(demo_place.java:17)
1 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
String 的索引從 開始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);
}
無論是負數還是正數都可以獲得長度
添加回答
舉報
0/150
提交
取消