0

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)

3
  • Note that Math.log10 returns NaN (Not a Number) for negative inputs. Commented Jul 25, 2019 at 7:44
  • 1
    This is not clear what you are asking. Are you trying to compute the number of digits in the number ? Commented Jul 25, 2019 at 7:46
  • If the intention is to convert the int to an byte, why not just number & 0xff? Commented Jul 25, 2019 at 8:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.