Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8825423
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T06:52:27+00:00 2026-06-14T06:52:27+00:00

I’ve created this simple compression class for a client server TCP data connection and

  • 0

I’ve created this simple compression class for a client server TCP data connection and it all looks fine to me with no build errors however I am getting a run time error that I cannot correct. The error I am getting is Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: -1.

Code:

import java.io.Serializable;
import java.util.ArrayList;

public class CompressedMessage implements Serializable
{   // this instance variable will store the original, compressed and decompressed message
    private String message;

    public CompressedMessage(String message)
    {   
        // begin by coding this method first - initialise instance variable message with the original message
        this.message = message;
    }

    public String getMessage()
    {   
        return this.message;

    }

    private boolean punctuationChar(String str)
    {   
        // Hint: check if the last character in the string is a punctuation
        int length = str.length();
        str = str.substring(length -2,length-1);

        if(str.equals(",") || str.equals("!") || str.equals(".") || str.equals("?"))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    private String getWord(String str)
    {   // Hint: if last character in string is punctuation then remove 

    if(punctuationChar(str)== true)
    {
        //remove punctuation of last char
        str = str.substring(0,str.length()-1);
    }

        return str;
    }


    public void compress()
    {   /* read through section 3 of the practical 5 document 
           to get you started. This is called by the server, 
           have a look at the server code where it is called */ 
        ArrayList<String> newMessage = new ArrayList<String>();


        String[] words = message.split(" ");  

        for (String word : words)  
        {  
            getWord(word);
            //if word has already appeared replace with position of previous word
            if(newMessage.contains(word))
            {
                String str = Integer.toString(newMessage.indexOf(word));
                str = str + " ";
                newMessage.add(str);
            }
            else
            {
                word = word + "";
                newMessage.add(word);
            }

         //if word had a punctuation at the end add it back in
         //System.out.println(word);  
        }  

            this.message = newMessage.toString();
            System.out.println("****************COMPRESSING*****************");
            System.out.println(newMessage);

    }

    public void decompress()
    {   /* read through section 3 of the practical 5 document 
           to get you started. This is called by the client,
           have a look at the client code where it is called */
           ArrayList<String> decompMessage = new ArrayList<String>();

           String[] words = message.split(" ");


           for (String word : words)  
        {  
            getWord(word);

            if(word.substring(0,1).matches("[0-9]"))
            {
              int num = Integer.parseInt(word);
              decompMessage.add(decompMessage.get(num));

            }
            else
            {
                decompMessage.add(word);
            }
        }

        this.message = decompMessage.toString();
        System.out.println("****************DECOMPRESSING*****************");
            System.out.println(decompMessage);  

    }
}

Error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1952)
    at CompressedMessage.punctuationChar(CompressedMessage.java:24)
    at CompressedMessage.getWord(CompressedMessage.java:40)
    at CompressedMessage.compress(CompressedMessage.java:61)
    at P5_Server.waitForData(P5_Server.java:72)
    at P5_Server.main(P5_Server.java:159)

I have tried changing the way a calculated the strings based on the length() but it didn’t reduce the errors.

Can anyone see what I’m doing wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T06:52:28+00:00Added an answer on June 14, 2026 at 6:52 am

    What if you str is length 0 (empty string ) or length 1? In that case str = str.substring(length -2,length-1); will result into exception.

    You need to put a length check before performing the substring:

        if(length > 1){
            str = str.substring(length-2,length-1);
        }
    

    Since you are trying to get only one character, I think you can simply do as:

        if(length > 1){
            str = String.valueOf(str.charAt(length-2))
        }
    

    Please make sure that str is not null otherwise put a null handling as well.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.