在java中查找字符串中的元音然后打印金额

时间:2015-10-15 02:05:23

标签: java

我必须编写一个程序,它接受一个字符串然后计算所有单独的元音。它应该打印出多少一个,一个,一个,一个,一个,另外一个。 我的代码如下

import java.util.*;

public class VowelsInString {

public static void main(String[] args) 
{

    Scanner scan = new Scanner(System.in);

    int placeInString = 0;
    int a = 0;
    int e = 0;
    int i = 0;
    int o = 0;
    int u = 0;
    int nV = 0;
    String myString;

    System.out.println("Enter a string.");
    myString = scan.nextLine();

    while(placeInString <= myString.length())
    {
        if(myString.charAt(placeInString) == 'a')
        {
            a ++;
        }
        else if(myString.charAt(placeInString) == 'e')
        {
            e ++;
        }
        else if(myString.charAt(placeInString) == 'i')
        {
            i ++;
        }
        else if(myString.charAt(placeInString) == 'o')
        {
            o ++;
        }
        else if(myString.charAt(placeInString) == 'u')
        {
            u ++;
        }
        else
        {
            nV ++;
        }

        placeInString ++;

    }
    System.out.println("Numbber of a's in string: " + a);
    System.out.println("Numbber of e's in string: " + e);
    System.out.println("Numbber of i's in string: " + i);
    System.out.println("Numbber of o's in string: " + o);
    System.out.println("Numbber of u's in string: " + u);
    System.out.println("Numbber of non-vowels's in string: " + nV);



}

}

我的输出是

输入字符串。 aaaaeeeeiiiooouuuuggdgds

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 24
    at java.lang.String.charAt(Unknown Source)
    at VowelsInString.main(VowelsInString.java:24)

我的问题是什么?我该如何解决?我是初学者的java类,我们刚开始循环。任何帮助表示赞赏。感谢。

3 个答案:

答案 0 :(得分:3)

 while(placeInString <= myString.length())

更改为

 while(placeInString <= myString.length()-1)

while(placeInString < myString.length())

字符串为0索引。如果您有一个长度为4的字符串,并尝试访问str.length()(即4)中的字符,那么您将尝试访问第5个元素,该元素超出范围。字符串中的最后一个字符始终位于索引str.length() - 1。

答案 1 :(得分:0)

可以应用的替代方法:

String  str="hi How Aa rEe YoOuU";   
System.out.println("No. of vowels: " + (str.length() - str.toLowerCase().replaceAll("a|e|i|o|u", "").length()));

输出:

No. of vowels: 10

答案 2 :(得分:0)

您可以使用逗号分隔您的变量声明,并且您可能更愿意使用for-each loop来避免在最后一次(var myapp = angular.module('point',['firebase']); myapp.factory('fact', function ($firebaseArray) { var ref = new Firebase("https://myangularl.firebaseio.com"); return $firebaseArray(ref); }) myapp.controller('financeCtrl', function ($scope,fact) { $scope.students = fact; $scope.add = function (data) { var name = $scope.name; var major = $scope.major; $scope.students.$add({ name: name, major: major }); $scope.name=""; $scope.major=""; }, $scope.remove = function(data) { $scope.students.$remove(data); } }); 之后)使用类似

的内容访问该字符
String.length() - 1