[英]Count all Vowels in a String
我正在開發一個計算字符串中元音數量的程序,但出現錯誤:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter String: ");
String string = input.nextLine();
string=string.toLowerCase();
System.out.println("Vowels: "+ vowels);
}
public static void countVowels(String string)
{
int i;
for (i=0;i<string.length();i++)
{
if (string.charAt(i) = "a" || string.charAt(i) = "e" || string.charAt(i) = "i" || string.charAt(i) = "o" || string.charAt(v) = "u")
{
vowels++;
}
}
}
}
哦,我想問一下沒有返回值/有返回值的方法是什么意思。 不確定上面的代碼是否有返回值。
你的代碼中有很多錯誤的東西。
在 Java 中,你用單引號表示一個字符,例如 'a' 'b' 等。
字符串是雙引號,是一個對象“a”、“b”。
您無法將 Char 與 String 進行比較。
您需要將 char 與 char 進行比較。
string.charAt(i) == 'a'
並且缺少雙等號。
大多數問題已由其他人回答,剩下的很少。
countVowels()
,您沒有調用函數countVowels()
並且在main
方法中聲明了可變vowels
,而不是在函數countVowels()
。
有返回值的方法:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter String: ");
String string = input.nextLine();
string=string.toLowerCase();
int vowels = countVowels(string); // calling function which returns a value.
System.out.println("Vowels: "+ vowels);
}
public static int countVowels(String string)
{
int i,vowels=0;
for (i=0;i<string.length();i++)
{
if (string.charAt(i) == 'a' || string.charAt(i) == 'e' || string.charAt(i) == 'i' || string.charAt(i) == 'o' || string.charAt(i) == 'u')
{
vowels++;
}
}
return vowels;
}
}
沒有返回值的方法:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
.... // same code as above
countVowels(string); // calling funtion, this doesnt return value
}
public static void countVowels(String string)
{
int i,vowels=0;
for (i=0;i<string.length();i++)
{
.... // same code as above
}
System.out.println("Vowels: "+ vowels);
}
}
您需要解決以下問題,
vowels
的范圍設置為方法級別,因此在main
方法之外不可用countVowels
永遠不會被調用=
用於代替比較==
" "
代替字符' '
我上面的代碼有很多問題。
一、主類甚至沒有調用方法類(countVowels)
其次,我使用雙引號" "
並將其稱為char
。 String 使用" "
,char 使用' '
第三,我使用了單個=
而不是==
下面是細化的代碼
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter String: ");
String string = input.nextLine();
string=string.toLowerCase();
countVowels(string);
}
public static void countVowels(String string) //method class, dito yung parang procedure nung pagbibilang ng vowels
{
int v;
int vowels = 0;
for (v=0;v<string.length();v++)
{
if (string.charAt(v) == 'a' || string.charAt(v) == 'e' || string.charAt(v) == 'i' || string.charAt(v) == 'o' || string.charAt(v) == 'u')
{
vowels++;
}
}
System.out.println("Vowels: "+ vowels);
}
}
如果您對替代方法感興趣,請嘗試此方法。
String str = "To be or not to be, that is the question.";
long count = str.chars().filter(ch->"aeiou".contains((char)ch+"")).count();
System.out.println(count);
印刷
13
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.