3

我为 COSC 课程制作的这个程序编译不正确,我不断收到错误消息:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:2

在 java.lang.String.substring(String.java:1765) 在 VowelCount.main(VowelCount.java:13)

这是我的代码:

import java.util.Scanner;

public class VowelCount {
 public static void main(String[] args) {
  int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
  String input, letter;
  Scanner scan = new Scanner (System.in);

  System.out.println ("Please enter a string: ");
  input = scan.nextLine();

  while (count <= input.length() ) {
   letter = input.substring(count, (count + 1));

   if (letter == "a") {
    a++; }
   if (letter == "e") {
    e++; }
   if (letter == "i") {
    i++; }
   if (letter == "o") {
    o++; }
   if (letter == "u") {
    u++; }

   count++;

  }
  System.out.println ("There are " + a + " a's.");
  System.out.println ("There are " + e + " e's.");
  System.out.println ("There are " + i + " i's.");
  System.out.println ("There are " + o + " o's.");
  System.out.println ("There are " + u + " u's.");
 }
}

据我所知,这应该有效,但为什么不呢?任何帮助都会很棒。谢谢!

4

5 回答 5

5

您可能需要取出行中的 =

while (count <= input.length() ) {

并做到

while (count < input.length() ) {

因为它导致子字符串读取超出字符串的长度。

=============== 但是我会添加一些额外的建议,即使它没有被要求:

不要使用 == 来比较字符串,使用

letter.equals("a")

反而。甚至更好,尝试使用

char c = input.charAt(count);

获取当前字符,然后像这样比较:

c == 'a'
于 2009-10-15T01:36:30.943 回答
0

我认为你的循环条件应该是count < input.length. 现在,最后一次迭代使用 运行count == length,因此substring在字符串中的最后一个字符之后为您的调用提供了一个起始索引,这是非法的。这些类型的边界错误在编写此类循环时非常常见,因此当您遇到此类错误时,最好对循环条件进行两次和三次检查。

此外,将字符串与==运算符进行比较通常不会满足您的要求。比较两个变量是否引用同一个对象。相反,您想要 test string1.equals(string2),它比较两个字符串的内容。

于 2009-10-15T01:38:13.240 回答
0

在所有人的帮助下修复它,尤其是文森特。谢谢!运行精彩。

import java.util.Scanner;

public class VowelCount {
    public static void main(String[] args) {
        int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
        String input;
        char letter;

        Scanner scan = new Scanner (System.in);

        System.out.print ("Please enter a string: ");
        input = scan.nextLine();

        while (count < input.length() ) {
            letter = input.charAt (count);

            if (letter == 'a')
                a++; 
            if (letter == 'e') 
                e++; 
            if (letter == 'i') 
                i++; 
            if (letter == 'o') 
                o++; 
            if (letter == 'u') 
                u++; 

            count++;

        }
        System.out.println ("There are " + a + " a's.");
        System.out.println ("There are " + e + " e's.");
        System.out.println ("There are " + i + " i's.");
        System.out.println ("There are " + o + " o's.");
        System.out.println ("There are " + u + " u's.");
    }
}
于 2009-10-15T01:45:37.210 回答
0

删除等号应该可以解决这个问题。

while (count < input.length()) {

并且由于您想获得一个字符,因此您应该这样做:

substr(count,1)

因为第二个参数实际上是长度,而不是索引。

于 2009-10-15T01:37:41.703 回答
0

在循环之前,请尝试以下

if(input.length()>0){
//you code
}
于 2017-04-20T11:48:10.010 回答