gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:16:42 29 4
gpt4 key购买 nike

我为 COSC 类(class)制作的这个程序编译不正确,我不断收到错误:

线程“main”中的异常 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.");
}
}

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

最佳答案

你可能需要去掉行中的=

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

并成功

while (count < input.length() ) {

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

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

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

letter.equals("a")

相反。或者更好的是,尝试使用

char c = input.charAt(count);

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

c == 'a'

关于java - 字符串索引越界? (Java,子串循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1569868/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com