本文介绍了字符串索引越界?(Java,子串循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

at java.lang.String.substring(String.java:1765) at 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.");
 }
}

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

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

推荐答案

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

You may need to take out the = in the line

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

并成功

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'

这篇关于字符串索引越界?(Java,子串循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:19