简体   繁体   English

为什么会出现java.lang.StringIndexOutOfBoundsException?

[英]Why am I getting java.lang.StringIndexOutOfBoundsException?

I want to write a program that prints words incrementally until a complete sentence appears. 我想编写一个程序,逐步打印单词,直到出现完整的句子。 For example : I need to write (input), and output: 例如:我需要编写(输入)并输出:

I 一世
I need 我需要
I need to 我需要
I need to write. 我要写

Here is my code: 这是我的代码:

public static void main(String[] args) {   
   String sentence = "I need to write.";
   int len = sentence.length();
   int numSpace=0;
   System.out.println(sentence);
   System.out.println(len);

   for(int k=0; k<len; k++){
      if(sentence.charAt(k)!='\t')
         continue;
      numSpace++;
   }

   System.out.println("Found "+numSpace +"\t in the string.");  

   int n=1;
   for (int m = 1; m <=3; m++) {      
      n=sentence.indexOf('\t',n-1);
      System.out.println("ligne"+m+sentence.substring(0, n));
   }
}

and this is what I get: 这就是我得到的:

I need to write. 我要写
16 16
Found 0 in the string. 在字符串中找到0。
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at 字符串索引超出范围:-1处
java.lang.String.substring(String.java:1937) at java.lang.String.substring(String.java:1937)在
split1.Split1.main(Split1.java:36) Java Result: 1 BUILD SUCCESSFUL split1.Split1.main(Split1.java:36)Java结果:1构建成功
(total time: 0 seconds) (总时间:0秒)

I don't understand why numSpace doesn't count the occurrences of spaces, nor why I don't get the correct output (even if I replace numSpace by 3 for example). 我不明白为什么numSpace不计算空格的出现,也不明白为什么我没有得到正确的输出(即使我将numSpace替换为3)。

  1. You don't have a \\t character, so indexOf(..) returns -1 您没有\\t字符,因此indexOf(..)返回-1
  2. You try a substring from 0 to -1 - fails 您尝试从0到-1的子字符串-失败

The solution is to check: 解决方法是检查:

if (n > -1) {
    System.out.prinltn(...);
}

Your loop looking for numSpace is incorrect. 您寻找numSpace循环不正确。 You are looking for a \\t which is a tab character, of which there are none in the string. 您正在寻找一个\\t ,它是一个制表符,字符串中没有。

Further, when you loop in the bottom, you get an exception because you are trying to parse by that same \\t , which will again return no results. 此外,当您在底部循环时,会得到一个异常,因为您尝试使用同一\\t进行解析,这将再次不返回任何结果。 The value of n in n=sentence.indexOf('\\t',n-1); n的值n=sentence.indexOf('\\t',n-1); is going to return -1 which means "there is not last index of what you are looking for". 将返回-1 ,这意味着“没有您要查找的内容的最后一个索引”。 Then you try to get an actual substring with the value of -1 which is an invalid substring, so you get an exception. 然后,您尝试获取值为-1的实际子字符串,它是无效的子字符串,因此会出现异常。

You are mistaken by the concept of \\t which is an escape sequence for a horizontal tab and not for a whitespace character (space). 您误以为\\t水平制表符而不是空白字符(空格)的转义序列。 Searching for ' ' would do the trick and find the whitespaces in your sentence. 搜索' '可以解决问题,并在句子中找到空格。

This looks like homework, so my answer is a hint. 这看起来像是作业,所以我的回答是一个提示。

Hint: read the javadoc for String.indexOf paying attention to what it says about the value returned when the string / character is not found. 提示:阅读String.indexOf的javadoc时要注意有关未找到字符串/字符时返回的值的说明。

(In fact - even if this is not formal homework, you are clearly a Java beginner. And beginners need to learn that the javadocs are the first place to look when using an unfamiliar method.) (实际上-即使这不是正式的功课,您显然也是Java的初学者。初学者需要了解,使用不熟悉的方法时, javadocs是查找的第一位。)

The easiest way to solve this I guess would be to split the String first by using the function String.split. 我想解决这个问题的最简单方法是先使用String.split函数拆分String。 Something like this: 像这样:

static void sentence(String snt) {
    String[] split = snt.split(" ");

    for (int i = 0; i < split.length; i++) {
        for (int j = 0; j <= i; j++) {
            if (i == 1 && j == 0) System.out.print(split[j]);
            else System.out.printf(" %s", split[j]);
        }
    }
}

As other people pointed out. 正如其他人指出的那样。 You are counting every characters except tabs(\\t) as a space. 您正在将制表符(\\ t)以外的每个字符都算作一个空格。 You need to check for spaces by 您需要检查空格

if (sentence.charAt(k) == ' ')
  1. \\t represents a tab . \\t代表制表符 To look for a space , just use ' ' . 要查找空间 ,只需使用' '
  2. .indexOf() returns -1 if it can't find a character in the string. .indexOf()如果在字符串中找不到字符,则返回-1。 So we keep looping until .indexOf() returns -1. 因此,我们一直循环直到.indexOf()返回-1。
  3. Use of continue wasn't really needed here. 这里实际上并不需要使用continue We increment numSpaces when we encounter a space. 遇到空格时,我们将递增numSpaces
  4. System.out.format is useful when we want to mix literal strings and variables. 当我们要混合文字字符串和变量时, System.out.format很有用。 No ugly + s needed. 没有丑女+ š需要。

String sentence = "I need to write.";
int len = sentence.length();
int numSpace = 0;   
for (int k = 0; k < len; k++) {
    if (sentence.charAt(k) == ' ') {
        numSpace++;
    }
}
System.out.format("Found %s in the string.\n", numSpace);
int index = sentence.indexOf(' ');
while(index > -1) { 
    System.out.println(sentence.substring(0, index));
    index = sentence.indexOf(' ', index + 1);
}
System.out.println(sentence);
}

Try this, it should pretty much do what you want. 试试这个,它几乎应该做您想要的。 I figure you have already finished this so I just made the code real fast. 我认为您已经完成了这一步,所以我使代码变得非常真实。 Read the comments for the reasons behind the code. 阅读注释以了解代码背后的原因。

public static void main(String[] args) {   
  String sentence = "I need to write.";
  int len = sentence.length();

  String[] broken = sentence.split(" "); //Doing this instead of the counting of characters is just easier...

  /* 
   * The split method makes it where it populates the array based on either side of a " " 
   * (blank space) so at the array index of 0 would be 'I' at 1 would be "need", etc.
   */

  boolean done = false;
  int n = 0;

  while (!done)  { // While done is false do the below

    for (int i = 0; i <= n; i++) { //This prints out the below however many times the count of 'n' is.

    /*
     * The reason behind this is so that it will print just 'I' the first time when
     * 'n' is 0 (because it only prints once starting at 0, which is 'I') but when 'n' is 
     * 1 it goes through twice making it print 2 times ('I' then 'need") and so on and so 
     * forth.
     */
      System.out.print(broken[i] + " ");
    }
    System.out.println(); // Since the above method is a print this puts an '\n' (enter) moving the next prints on the next line

    n++; //Makes 'n' go up so that it is larger for the next go around

    if (n == broken.length) { //the '.length' portion says how many indexes there are in the array broken

    /* If you don't have this then the 'while' will go on forever. basically when 'n' hits
     * the same number as the amount of words in the array it stops printing.
     */
      done = true;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM