ja jaaaa
ja jaaaa

Reputation: 115

160 characters limit for SMS messages

I have one field which can contain from 1 to unlimited number of characters. I want to restrict to send maximum 3 messages (so minimum 1 maximum 3). So it is maximum 480 characters. I want to list (write in output) each message separately (from 0-160; 160-320; 320-480).All over the 480 is not my concern.

My class works when there are on example 500 characters but for small number of characters like in example it wont work.

 String message="message to sent";
 int m=message.length();


b=160;
int c=m/b;


int bi=0;
int ei=160;



for (int i = 0; i < c; i++) {
    while (ei<=480)
    {
    System.out.println("\n"+message.substring(bi, ei));
    bi=bi+160;
    ei=ei+160;
    }
}

what do I have to correct to work this completely and for small number of characters in message and for large messages? thank you

Upvotes: 0

Views: 665

Answers (3)

zakinster
zakinster

Reputation: 10688

int c=m/b;

c will be rounded down while casted to int so it will be the number of sms - 1 if m < b, you should write :

int c = (int) Math.ceil((double) m/b);

Or, since m and b are positives :

int c = (m+b-1)/b;

Besides, i don't understand the purpose of your double loop, if you want to display each message block you can loop over c :

for(int i = 0; i < c && i < 3; i++) {
    int start = i*b;
    int end = Math.min( (i+1)*b, m);
    System.out.println( message.substring(start, end) );
}

Or you can loop over an offset :

for(int offset = 0; offset<b*c && offset<b*3; offset+=b) {
    System.out.println( message.substring(offset , Math.min(m, offset+b) ) );
}

But you can't do both.

Upvotes: 3

Vincent van der Weele
Vincent van der Weele

Reputation: 13177

There is quite a lot wrong with this code.

  1. As zakinster already answered: m/b rounds down to 0 if m < b, so your for loop is never executed
  2. Your double loop is unnecessary and will lead to trouble as soon as you solve problem 1.
  3. You don't test for the end of the message

You would do better to replace the last double loop by:

int offset = 0;
int length;

while (offset < 480 && offset < m) {
    length = Math.min(160, m - offset);
    System.out.println("\n"+message.substring(offset, offset+length));
    offset += 160;
}

Upvotes: 0

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18148

You need message.substring(bi, ei < m ? ie : m)); for the case when m isn't a multiple of 160

Also, exit the for loop when you reach the end of the message

Upvotes: 0

Related Questions