gpt4 book ai didi

java - 使用 while 循环删除字符,直到达到计数,Java 不工作

转载 作者:行者123 更新时间:2023-12-01 09:20:29 26 4
gpt4 key购买 nike

我试图在循环中执行此操作,从字符串中删除元音,直到达到正确的字符数(140),但是它不起作用。我不确定 do while 循环是否正在工作,然后在满足条件后停止,但如果是这种情况,一旦满足条件,我如何运行其余的代码?提前致谢!这是我正在使用的代码:

public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
int length = toCompress.length();
System.out.println(length);;

do {
toCompress = toCompress.replaceAll("[AEIOUaeiou]", "");
}while(length >= 140);


System.out.println("Compressed phrase: ");
System.out.println(toCompress);
int length2 = toCompress.length();
System.out.print(length2);;
scan.close();

}

最佳答案

您需要一次删除一个元音,直到达到 140 长度。现在,执行 toCompress = tocompress.replaceAll("[AEIOUaeiou]", "") 后,您不会更新长度正确做法:

public static void main(String[] args){
Scanner scan = new Scanner( System.in );
String[] vow={"A","a","O","o","E","e","U","u","I","i"};
List<String> vowels=Arrays.asList(vow);
System.out.println("Enter the phrase to be shortened: ");
String toCompress = scan.nextLine();
int length = toCompress.length();
System.out.println(length);

String compressed="";

while(length >= 140&&compressed.length()<140){
String firstLetter=toCompress.substring(0,1);
//if the first letter is not a vowel, add it to the compressed string
if(!vowels.contains(firstLetter)) compressed.concat(firstLetter);
//remove the first letter from toCompress
toCompress=toCompress.substring(1);
//update the length to the new value
length=compressed.length()+toCompress.length();
}
//After reaching 140 characters, concatenate the rest of toCompress to compressed
compressed.concat(toCompress);

System.out.println("Compressed phrase: ");
System.out.println(compressed);
System.out.print(compressed.length());
scan.close();
}

关于java - 使用 while 循环删除字符,直到达到计数,Java 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com