Reputation: 3
My problem is that I can't counting properly length of int, when it's negative.
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 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:
Variable length is: 0 digits This is: -1234567890 We have negative variable -1234567890 Last digit (10): 0 Existing result is: 0
This is result when I have -123456789 nine digit:
Variable length is: 0 digits This is: -123456789 We have negative variable -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)
Upvotes: 0
Views: 184
Reputation: 14678
The index for a String starts from 0
, so when you do;
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;
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.
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
Upvotes: 1