【问题标题】:StringIndexOutOfRangeException字符串 IndexOutOfRangeException
【发布时间】:2013-10-30 02:38:00
【问题描述】:

我正在做一个简单的程序来检查用户输入的单词是否是外来语言的一部分。 我得到一个索引超出范围的错误消息......有什么帮助吗? “字符串索引超出范围=”但是输入了许多字母。

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

    public class AlienWords{
       public static void main(String[]args) throws IOException {
       Scanner scan = new Scanner(in);

          out.print("Enter a word: ");
          String str = scan.nextLine();

          char d = str.charAt(str.length());

       int florb = 0;
       int zith = 0;
       int wooble = 0;
       int zarf = 0;

             if (str.charAt(0) == str.charAt(str.length())){
          florb++;
       }
             if (str.indexOf("cj") != -1 || str.indexOf("wq") != -1) {
          wooble++;
       }
             if (str.length() % 2 == 1 && str.indexOf('z') == -1){
          zith++;
       }
             if (str.length() % 2 == 0 && str.indexOf('k') == -1){
          zith++;
       }
             if(Character.isUpperCase(d)){
          zarf++;
       }
             else {
          out.println("This is not an alien word.");
             } 

          }
       }

【问题讨论】:

  • 以后,请发布确切的堆栈跟踪。它将包括行号。

标签: java string indexoutofboundsexception


【解决方案1】:

str.length()-1 是你要找的。​​p>

您说您收到的错误消息是:"String index out of range =" however many letters are inputted.。在这种情况下,“无论输入多少字母”是您的编译器告诉您它试图访问的索引(但超出范围)。 Strings 的索引从 0 开始,因此,最后一个字符的索引将比 String 中的字符总数少 1。

【讨论】:

  • 谢谢,帮了很多忙@nhgrif。
  • @user2934559 没问题,请务必将答案标记为已接受,以便您的问题可以标记为已回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 2012-06-11
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多