我制作了一個 java 程式來計算字串中元音的數量,我需要使用一個或多個 for 回圈來為專案執行此操作。問題是它在輸入字串后沒有做任何事情,或者只是花費了太長時間:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a string to count the vowels>> ");
String x = s.nextLine();
int numVowels = countVowels(x, "aeiou");
System.out.println(numVowels);
}
static int countVowels(String x, String vowels)
{
int count = 0;
String z = x.toLowerCase();
for (int i = 0; i <= vowels.length() - 1; i )
{
if (i == vowels.length() - 1)
{
for (int n = z.indexOf(vowels.substring(i)); n != -1; count )
{
z.replace(vowels.substring(i), "");
}
}
else if (z.indexOf(vowels.substring(i, i 1)) != -1)
{
for (int n = z.indexOf(vowels.substring(i, i 1)); n != -1; count )
{
z.replace(vowels.substring(i, i 1), "");
}
}
}
return count;
}
}
我減少了回圈次數,因為原作非常混亂。我認為問題出在嵌套回圈上,但我還沒有嘗試在本地編譯器上運行它,只有在線 IDE。我聽說它對編譯時間產生了很大的影響。
uj5u.com熱心網友回復:
這是一個無限回圈:z如果您只使用z.replace. 由于字串在 Java 中是不可變的,因此您不能僅通過呼叫方法來更改它,您必須重新分配它:
z = z.replace(...)
uj5u.com熱心網友回復:
我冒昧地使用 while 回圈而不是 for 回圈,因為這個想法是繼續回圈直到找到、計數和一一替換所有元音。
static int countVowels(String x, String vowels) {
int count = 0;
String z = x.toLowerCase();
for (int i = 0; i < vowels.length(); i ) {
String vowel = Character.toString(vowels.charAt(i));
while (z.indexOf(vowel) != -1) {
count ;
z = z.replaceFirst(vowel, "");
}
}
return count;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/341812.html
上一篇:Azure突觸分析并行插入臨時表
