字符串索引越界?(Java,子串循环)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1569868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:07:57  来源:igfitidea点击:

String index out of bounds? (Java, substring loop)

javasubstringwhile-loop

提问by Brad

This program I'm making for a COSC course isn't compiling right, I keep getting the error:

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

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2

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

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

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

Here's my code:

这是我的代码:

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.");
 }
}

To my knowledge this should work, but why doesn't it? Any help would be great. Thank you!

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

回答by Vincent Ramdhanie

You may need to take out the = in the line

您可能需要去掉该行中的 =

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

and make it

并使它

while (count < input.length() ) {

because it is causing the substring to read beyond the length of the string.

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

=============== But I'll add a few extra bits of advice even though its not asked for:

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

do not use == to compare strings, use

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

letter.equals("a")

instead. Or even better, try using

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

char c = input.charAt(count);

to get the current character then compare like this:

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

c == 'a'

回答by mauris

Removing the equal sign should fix that.

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

while (count < input.length()) {

while (count < input.length()) {

and since you want to get a single character, you should do this:

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

substr(count,1)

substr(count,1)

because the 2nd parameter is actually length, not index.

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

回答by bcat

I think your loop condition should be count < input.length. Right now, the last iteration runs with count == length, so your substringcall is given a start index after the last character in the string, which is illegal. These type of boundary errors are very common when writing such loops, so it's always good to double- and triple-check your loop conditions when you encounter a bug like this.

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

Also, comparing strings with the ==operator usually won't do what you want. That compares whether or not the two variables reference the same object. Instead, you want to test string1.equals(string2), which compares the contents of the two strings.

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

回答by Brad

Fixed it with help from everyone, and especially Vincent. Thank you! Runs wonderfully.

在所有人的帮助下修复了它,尤其是文森特。谢谢!运行得很好。

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.");
    }
}

回答by Arsalan Khan

Before loop,try below

在循环之前,请尝试以下

if(input.length()>0){
//you code
}