【问题标题】:My program has a runtime error: exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27我的程序出现运行时错误:线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:27
【发布时间】:2015-02-21 07:16:08
【问题描述】:

这是我收到的完整错误消息:

exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
	at java.lang.String.charAt(String.java:646)
	at Main.main(Main.java:268)
	at Ideone.assertRegex(Main.java:110)
	at Ideone.test(Main.java:42)
	at Ideone.main(Main.java:28)

我在 DrJava 中为类分配编写了我的程序并且它可以工作,但是当我将我的代码输入到他们的代码运行器中时,我得到了运行时错误。我的代码如下:

import java.io.*;
import static java.lang.System.*;

import java.util.Scanner;

class Main{

     public static void main (String str[]) throws IOException {

       Scanner scan = new Scanner(System.in);
       
       System.out.println("Please enter a tweet:");
       String tweet = scan.nextLine();
       
       int length = tweet.length();
       if(length > 140){
         System.out.println("Excess Characters: " + (length - 140));}
       else{
       System.out.println("Length Correct"); 
       
       int countera = 0;
for( int i=0; i<tweet.length(); i++ ) {
    if( tweet.charAt(i) == '#' ) {
      i++;
      if (( tweet.charAt(i) != ' ' ) && ( tweet.charAt(i) != '\t' ))
        countera++;
    } 
}
       int counterb = 0;
for( int i=0; i<tweet.length(); i++ ) {
    if( tweet.charAt(i) == '@' ) {
      i++;
      if (( tweet.charAt(i) != ' ' ) && ( tweet.charAt(i) != '\t' ))
        counterb++;
    } 
}

int counterc = 0 ;
String search = "http://";

for ( int i = -1 ; ( i = tweet.indexOf( search, i + 1 ) ) != -1 ; counterc ++ );


       System.out.println("Number of Hashtags: " + countera);
       System.out.println("Number of Attributions: " + counterb);
       System.out.println("Number of Links: " + counterc);
       }
     }
} 
    

【问题讨论】:

  • 您可能希望使用Character.isWhitespace(c) 来测试白人步伐作为“单词”之间的分隔符,而不是' ''\t'

标签: java string runtime-error


【解决方案1】:

好吧,你写了

for( int i=0; i<tweet.length(); i++ ) {
    if( tweet.charAt(i) == '#' ) {
        i++;
        if (( tweet.charAt(i) != ' ' ) && ( tweet.charAt(i) != '\t' )) {
          //rest of code
        }
    }
}

所以当i 达到tweet.length() - 1 时,你把它加1,所以它变成tweet.length()。然后您调用tweet.charAt(i),这会导致您遇到异常。

请记住,字符串的第一个字符位于索引 0,最后一个字符位于索引 length - 1

【讨论】:

  • 我是一个编程新手,我真的不明白为什么这会导致异常或错误。该程序在 DrJava 中运行得很好,所以并不是说它不起作用。
猜你喜欢
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多