super95
super95

Reputation: 103

Removing first digit from int, but keeping leading zeros

I need to write code for removing the first digit if an int is more than 3 digits. For example if I have 1055 then the output would be 055. My current code removes the first digit but the problem is it also removes the zeros and outputs 55 instead of 055. How would I got about to fix this? The variable that I'm referring to is the checksum

 int checksum = 0;
 int l = message.length();

 for (int i = 0; i < l; i++) { 3
   checksum += message.charAt(i);
 }
 if (checksum >= 1000) {
   checksum = Integer.parseInt(Integer.toString(checksum).substring(1));
 }
 physicalLayer.sendFrame("(" + message + ":" + checksum + ":.)");

Upvotes: 2

Views: 1123

Answers (2)

Saddeep Mihiranga
Saddeep Mihiranga

Reputation: 33

You mention if the it is more than 4 digits then

int number = 1055;

    String text_no = Integer.toString(number);
    //System.out.println(text_no.substring(1,3));
    if(text_no.length() > 4) {
        System.out.println(text_no.substring(1));
    }

But "1055" has only 4 digit then if condition does not work if you need to check only 4 digit and more that for digits then this will work

int number = 1055;

        String text_no = Integer.toString(number);
        //System.out.println(text_no.substring(1,3));
        if(text_no.length() >= 4) {
            System.out.println(text_no.substring(1));
        }

Upvotes: 0

Teddy
Teddy

Reputation: 4223

You obviously cannot keep leading zeros in int data type. So, keep the result in a String copy

int checksum=0;
int l= message.length();

for (int i = 0; i < l; i++) { 
checksum+= message.charAt(i);

}

String sChecksum = Integer.toString(checksum);
if(checksum>=1000){
sChecksum= sChecksum.substring(1);   

}


physicalLayer.sendFrame("("+message+":"+sChecksum+":.)");

Upvotes: 1

Related Questions