【问题标题】:Error:Exception in thread "main" java.lang.StringIndexOutOfBoundsException错误:线程“主”java.lang.StringIndexOutOfBoundsException 中的异常
【发布时间】:2013-07-11 14:03:57
【问题描述】:

我一直在尝试执行这个程序,很多人会觉得它有点没用。尽管如此,我一直收到此错误:执行时线程“main”java.lang.StringIndexOutOfBoundsException 中的异常。此程序是查找元音、辅音、特殊字符等的数量,我最近收到此错误。请帮帮我。这是什么错误以及如何从我的代码中删除它。提前致谢。

import java.io.*;
public class numberof {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter string");
String str=br.readLine();
int vowel=0,consonant=0,upcase=0,locase=0,special=0,dig=0;
int l=str.length();
for(int in=1;in<=l;in++){         //This also is being displayed as an error
    char c=str.charAt(in);            //This is the error Line.
    if(c>=65||c<=90||c>=97||c<=123){
        if(c=='a'||c=='A'||c=='e'||c=='E'||c=='o'||c=='O'|c=='u'||c=='U'){
            vowel++;
            if(c>=65 && c<=90){
                upcase++;
                }
            else{
                locase++;
              }
        }
        else{
            consonant++;
            if(c>=65 && c<=90){
                upcase++;
            }
            else{
                locase++;

                    }
                }

            }
    else if(c>=48 && c<=57){
        dig++;
        }
    else{
        special++;
    }

    }
    System.out.println(upcase+" "+locase+" "+vowel+" "+consonant+" "+dig+" "+special);
}
   }

【问题讨论】:

    标签: java string counter bufferedreader


    【解决方案1】:
    for(int in=1;in<=l;in++)
    

    应该是

    for(int in=0;in<l;in++)
    

    数组索引从零开始(in =0 假设您希望从第一个元素开始)

    编辑:

    lString[] 的长度,让我们说5 分成a[0], a[1], a[2], a[3], a[4]

    如果您观察,现在您可以从 0(或)1(或)2 开始,但最多只能达到 a[4],当您使用 in &lt;= 时,循环将检查直到抛出的 a[5] indexoutofBounds 异常。

    【讨论】:

      【解决方案2】:

      在您的 for 循环中,您从索引 1 开始并在小于或等于时循环。

      for (int in = 1; in <= l; in++) {}
      

      这意味着你将循环 2 比你应该做的多。所以应该是:

      for (int in = 0; in < l; in++) {}
      

      数组索引是从零开始的,所以它从 0 循环到长度,而不是从 1 到长度。

      另一种写法是这样的:

      for(int i = 0; i < str.length(); i++) {}
      

      大多数 Java 开发人员会发现这更容易阅读。

      【讨论】:

        【解决方案3】:

        您想从第一个字符开始搜索所有字符串中的元音吗?使用for(int in=0; in&lt;l; in++)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-10
          • 2014-06-19
          • 2015-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-20
          相关资源
          最近更新 更多