My for loop for my string compression is a bit off. I have been working on this assignment the past 5 days and I can't figure out for the life of me what is wrong. Can someone help me out?
For example, I passed over the string "TTTTrrrEe"
and instead of getting T4r3Ee
, I'm getting T4r3EeTT
. I don't know why it jumps back to the beginning of the string like that, but I am getting closer.We can only use charAt
,equals
,length
, and substring
from the string class.
Can someone help guide me in the right direction by helping to correct my logic? I still want to try and code this myself, seeing as how it is an assignment.
public static String compress(String s){
int count = 0;
String temp = s.substring(0,1);
for(int i = 0; i < s.length(); i++){
if(i !=s.length()-1){
if(temp.equals(s.substring(i,i+1))){
count++;
}else{
if(count < 1){
System.out.print(s.substring(i,i+2));
System.out.print(temp.substring(0,1) );
}else{
System.out.print("" + temp.substring(0,1) + count);
i--;
temp = s.substring(count,count+1);
System.out.println(" temp is now " + temp);
count = 0;
//i--;
}
}
}
}
System.out.println(temp);
return temp;
}
Since this is a learning exercise, I wouldn't try fixing your code, just point out a few things to work on to get it right:
if (i !=s.length()-1)
condition inside the loop becomes unnecessary if you change your for
loop condition to i < s.length()-1
i
by calling char ch1 = s.charAt(i)
, and compare two characters using ==
operator, rather than calling equals()
on them.count
is zero (your count < 1
condition is equivalent to count == 0
) you print both the current character and the character after it, in addition to the first character of temp
followed by the count. This does not look correct.temp
as you go through the loop, you set it on each iteration. This does not look correct.temp
as you go through the loop is using StringBuilder
and append()
, instead of using a plain String
, and performing concatenations.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With