Reputation: 35
I am new to java programming. This snippet calculates no of letters in each word and stores it as a string(excluding the spaces) but it is only calculating till "large" and not counting no of letters in "container".
class piSong
{
String pi = "31415926535897932384626433833";
public void isPiSong(String exp)
{
int i,count=0;
String counter = "";
String str;
System.out.println(exp.charAt(25));
for(i=0;i<exp.length()-1;i++)
{
if(Character.isWhitespace(exp.charAt(i)))
{ str = Integer.toString(count);
counter += str;
count = 0;
continue;
}
count++;
}
System.out.println(counter);
}
}
public class isPiSong{
public static void main(String[] args)
{
piSong p = new piSong();
String exp = "can i have a large container";
p.isPiSong(exp);
}
}
expected output:314157
current output: 31415
Upvotes: 0
Views: 238
Reputation: 2251
String counter = "";
String[] array = exp.split(" ");
for(String s: array){
counter += Integer.toString(s.length);
}
The second line splits the String into an array of strings (splits using each instance of a space in the String). The loop goes through each individual String in the array and adds its length to the counter String.
It's preferable to use a StringBuilder
instead of +=
to append to a String.
StringBuilder sb = new StringBuilder();
String[] array = exp.split(" ");
for(String s: array){
sb.append(Integer.toString(s.length));
}
String counter = sb.toString();
But both will do the same.
Upvotes: 0
Reputation: 14471
There are 2 things you should fix.
In your for loop, your condition is i<exp.length()-1
. Why? You obviously want to include the last character also (which is charAt(exp.length() -1)
), so you condition should either be i <= exp.length() -1
or i < exp.length()
.
You logic is to count the letters whenever you encounter a whitespace. But after counting the last word, you dont have a whitespace. That's why it's not counting the last word.
To Fix, append count
to counter
after the loop.
// Loop ends here
counter += count;
System.out.println(counter);
Upvotes: 3