我正在開發一個計算字串中元音數量的程式,但出現錯誤:
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 ;
}
}
}
}
哦,我想問一下沒有回傳值/有回傳值的方法是什么意思。不確定上面的代碼是否有回傳值。
uj5u.com熱心網友回復:
你的代碼中有很多錯誤的東西。
在 Java 中,你用單引號表示一個字符,例如 'a' 'b' 等。
字串是雙引號,是一個物件“a”、“b”。
您無法將 Char 與 String 進行比較。
您需要將 char 與 char 進行比較。
string.charAt(i) == 'a'
并且缺少雙等號。
uj5u.com熱心網友回復:
您需要解決以下問題,
- 變數的范圍
vowels設定為方法級別,因此它在main方法之外不可用 - 該方法
countVowels永遠不會被呼叫 - 使用賦值運算子
=代替比較== - 字串文字用于
" "代替字符' '
uj5u.com熱心網友回復:
我上面的代碼有很多問題。
一、主類甚至沒有呼叫方法類 (countVowels)
其次,我使用雙引號" "并將其稱為char. 字串使用" "和字符使用' '
第三,我用的是single=而不是==
下面是細化的代碼
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);
}
}
uj5u.com熱心網友回復:
大多數問題已經被其他人回答了,剩下的很少。
即,您沒有呼叫您的函式,countVowels()并且您已經vowels在mainmethod 中宣告了您的變數,而不是在您的 function 中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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347836.html
