-3

To further explain my question I have a method that prints the length of the String that user inputs. Im trying at the moment if i enter a string "hello" the out is '05'.

If I enter a string that is more than 100 characters the out put would be '100','101','305' and so on. So to clarify how do I make it so that if the string is more than 100 that it will not be allowed and cause an error?

The main part of code i am conerned about is: String.format("%02d", message.length())

At the moment it if the string length is less than 10 it displays a 0 infront of the number. For example the string "hello" displays 05 instead of 5.

I hope i am on the right track, any help will be apperciated

Thanks

public void sendMessage(String message) throws ProtocolException
{ physicalLayer.sendFrame("<" + "E" + "-" + **String.format("%02d", message.length())** + "-" + message +
    "-" + sum%100 + ">");
}
Javon
  • 1
  • 1

2 Answers2

1

how do I make it so that if the string is more than 100 that it will not be allowed and cause an error?

    public void sendMessage(String message) throws ProtocolException, Exception
    { 

    // Check the length and throw an Exception if more than 100
    if (message.length()>100)
    throw new Exception("Length is more than 100");

    physicalLayer.sendFrame("<" + "E" + "-" + **String.format("%02d", message.length())** + "-" + message +
        "-" + sum%100 + ">");
    }
-1

Take the string.length(), or if you want to take first 100 letters:

String first100 = s.substring(0, Math.min(s.length(), 100));