请帮我完成我的DrJava代码。我对如何完成它很困惑

时间:2012-08-20 00:01:24

标签: java drjava

设计并实现一个从用户读取字符串的应用程序,然后确定并打印出现在字符串中的元音和辅音的数量。在循环中使用switch语句。

典型的程序输出可能是:

Enter a sentence
> My dog has fleas!
Sentence is : My dog has fleas!
VowelVount is : 4
ConsonantCount is : 9

我的代码是:

import java.util.Scanner;

public class VnC{

  public static void main(String [] args){
    String text;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a sentence");
    text = scan.nextLine();
    System.out.println("Sentence is : " + text);
    text = text.toLowerCase();
    switch(text) {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
        vowelCount++;
        System.out.println("VowelCount : " + vowelCount);
        break;
      default:
        consonanyCount++;
        System.out.println("ConsonantCount is : " + consonantCount);
        break;
    }
  }

}

3 个答案:

答案 0 :(得分:1)

你走在正确的道路上,几乎就在那里。您需要遍历输入字符串中的所有字符(text)。为此使用for循环,并打开每个字符而不是整个字符串。

答案 1 :(得分:0)

看看这个。可能有帮助:

import java.util.Scanner;

public class XX{

  public static void main(String [] args){
    String text;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a sentence");
    text = scan.nextLine();
    System.out.println("Sentence is : " + text);
    text = text.toLowerCase();
    int vowelCount = 0 ;
    int consonantCount = 0 ;
    text = text.replaceAll("[-+.^:, !]",""); // remove chars that you don't want to count

    for(int i = 0; i < text.length() ;i++ ){
        if(text.charAt(i)== 'a' ||text.charAt(i)== 'e' ||text.charAt(i)== 'i' ||text.charAt(i)== 'o' || text.charAt(i)== 'u')
            vowelCount++;
            else
            consonantCount++;
    }

    System.out.println("VowelCount : " + vowelCount);
    System.out.println("ConsonantCount is : " + consonantCount);
    }

    }

答案 2 :(得分:-1)

for (char ch : text.toCharArray()) { 
  switch(ch) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
      vowelCount++;
      break;
    default:
      consonanyCount++;
      break;
  }
} 
System.out.println("VowelCount : " + vowelCount);
System.out.println("ConsonantCount is : " + consonantCount);