我需要我的输出只有 5 个字符长,不包括删除的元音。目前我的代码正在计算输入长度并返回减去元音的数字。这可能会令人困惑。如果我输入“idontthinkso”,它只会返回“dnt”,而不是我希望它打印出的“dntth”。顺便说一句,我不允许使用 Stringbuilder 或类似的东西,只能使用循环,所以请原谅代码。我怎样才能解决这个问题?这是我的代码:
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);
}
}
最佳答案
我非常非常赞成为此使用 while 循环,但既然您说过只能使用 for 循环...
问题是,即使检测到元音,您的循环也会迭代直到 i = 5。我们需要一种方法来告诉循环假装从未发生过。你不能递减 i,否则你将永远卡在同一个字符上。
这就是我的想法,我决定简单地增加 tweetLengthAllowed
来抵消 i 增量。
import java.util.Scanner;
public class Main {
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) { //Must be a for loop
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;
tweetLengthAllowed++; //Allows the loop to continue for one more interation
} //end if
else{
s = s += c;
f = 0;
}//end else
} //end for
System.out.println(s);
} //end main
} //end class
另外,如果您要使用一大串 OR,请帮自己一个忙,并使其更具可读性,就像我上面所做的那样。
关于java - 使用循环从输入字符串中删除元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840085/