I need my output to only be 5 characters long NOT counting the removed vowels. Currently my code is counting the input length and returning that number minus the vowels. This might be confusing. If I input "idontthinkso" it only returns "dnt" instead of what I want it to print out which is "dntth". Btw, I'm not allowed to use Stringbuilder or anything like that, only a loop, so forgive the code. How can I fix this? Here is my code:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for (int i = 0; i < tweetLengthAllowed; i++) {
char c = input.charAt(i);
if (c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u' ||
c == 'A' ||
c == 'E' ||
c == 'I' ||
c == 'O' ||
c == 'U') {
f = 1;
} else {
s = s += c;
f = 0;
}
}
System.out.println(s);
}
}
Output:
I'm very much in favor of using a while loop for this, but since you stated you can only use a for loop...
The problem is that your loop will iterate until i = 5, even if a vowel is detected. We need a way to tell the loop to pretend that never happened. You can't decrement i, or you'll be stuck at the same character forever.
Here's what I came up with, I decided to simply increment the
tweetLengthAllowed
to negate the i increment.Also, if you're going to use a big chain of ORs, please do yourself a favor and make it more readable as I did above.
You can do this simpler. Here I iterate every char in the input and break if it reaches the limit:
Run output: