我有这个课程,我试图用它来查找字符串中的元音数量和辅音数量。
import java.lang.String;
public class vowelsAndConsonantsClass
{
private int vowels;
private int consonants;
public vowelsAndConsonantsClass(int vwls, int cons)
{
vowels = vwls;
consonants = cons;
}
public void numberOfVowels(String str)
{
int vwls = 0;
for(int i=0; i>str.length(); i++)
{
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u' || str.charAt(i) == 'y');
vwls++;
}
}//end numberOfVowels
public void numberOfConsonants(String str)
{
int cons = 0;
for(int i=0; i>=str.length(); i++)
{
if(str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u' || str.charAt(i) != 'y');
cons++;
}
}//end numberOfConsonants
public int getNumberOfVowels()
{
return vowels;
}
public int getNumberOfConsonants()
{
return consonants;
}
}//end class
我在收到错误时尝试使用此测试输入。我会评论它所在的线。
import java.util.Scanner;
import java.lang.String;
public class testVowelsAndConsonants
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice;
System.out.println("Please enter a string.");
String str = keyboard.nextLine();
choice = menu(keyboard);
Character.toLowerCase(choice);
switch(choice)
{
case 'a':
System.out.println(vowelsAndConsonantsClass.getNumberOfVowels());//ERROR ON THIS LINE
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':System.exit(0);
}
}
public static int menu(Scanner keyboard)
{
int choice;
System.out.println("Enter a to count the number of vowels in the string.\n"+
"Enter b to count the number of consonants in the string.\n"+
"Enter c to count both the vowels and consonants in the string.\n"+
"Enter d to enter another string.\n"+
"Enter e to Exit.\n");
do
{
choice = keyboard.nextInt();
}
while(choice<1||choice>6);
return choice;
}//End menu
}
请注意,我没有100%完成测试数据。一旦我理解了错误,我就会完成它。提前谢谢。
答案 0 :(得分:1)
您不能通过类名称(静态调用)调用非静态方法/成员。 我建议你实例化该类,然后调用非静态方法:
vowelsAndConsonantsClass v = new vowelsAndConsonantsClass(0, 0);
v.numberOfVowels(str);
System.out.println(v.getNumberOfVowels());
答案 1 :(得分:0)
您正尝试在此行上以静态方式调用非静态方法:
vowelsAndConsonantsClass.getNumberOfVowels())
根据您的需要,创建vowelsAndConsonantsClass
的实例或将getNumberOfVowels
标记为static
。
答案 2 :(得分:0)
System.out.println(vowelsAndConsonantsClass.getNumberOfVowels());
你可以使用类名来引用类的静态方法,就像你使用它一样
因为getNumberOfVowels()
中的vowelsAndConsonantsClass
不是静态的,您会收到此错误
详细了解方法依据here