Write your code in the file Compress java. Your code should go into a method wit
ID: 3805415 • Letter: W
Question
Write your code in the file Compress java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method: public static String compress (String original){} Run-length encoding (RLE is a simple "compression algorithm" (an algorithm which takes a block of data and reduces its size, producing a block that contains the same information in less space). It works by replacing repetitive sequences of identical data items with short "tokens that represent entire sequences. Applying RLE to a string involves finding sequences in the string where the same character repeats. Each such sequence should be replaced by a "token consisting of. the number of characters in the sequence the repeating character lf a character does not repeat, it should be left alone. For example, consider the following string: eeeeerrtyyyyyaqqawEEry TTTT After applying the RLE algorithm, this string is converted into: q9w5e2rt5y4qw2er3t In the compressed string, "9w" represents a sequence of 9 consecutive lowercase "w" characters. "5e' represents 5 consecutive lowercase "e"characters, etc. Write a method called compress that takes a string as input, compresses it using RLE, and returns the compressed string. Case matters uppercase and lowercase characters should be considered distinct. You may assume that there are no digit characters in the input string. There are no other restrictions on the input-it may contain spaces or punctuation. There is no need to treat non-letter characters any differently from letters.Explanation / Answer
import java.util.Scanner;
public class Compress{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter string: ");
String str = sc.nextLine();
System.out.println("Input: " + str);
String compressed = compress(str);
System.out.println("Compressed: " + compressed);
}
public static String compress(String str )
{
String compressed = "";
char ch=0;
int count=1;
for (int x = 0; x < str.length(); x++) {
if (ch == str.charAt(x)){
count = count + 1;
} else {
compressed = compressed + ch;
if(count != 1){
compressed = compressed + count;
}
ch = str.charAt(x);
count = 1;
}
}
compressed = compressed + ch;
if(count != 1){
compressed = compressed + count;
}
return compressed;
}
}
The main menthod gets the string from user input through the Scanner class.
The compress menthod takes the input String and then counts the sequence of the string and their counts of occurence and then finally print them by compressing by concatenating their counts after the respective character.
And then finally returns the String .
Thanks
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.