从数组的索引中检索字符串,但它不起作用

时间:2016-11-12 22:09:40

标签: java arrays for-loop

所以,我的代码应该在输入文件中查看,它包含的字符串,在有空格的地方分割它们并分别输出字符串。我尝试使用数组来分配那些我拆分为变量的字符串,这样我可以在我想要打印它们时访问它们但是我一直在使用,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Coma.main(Coma.java:26)

有人可以帮帮我吗?请原谅我对这个问题的格式化,因为这是我第一次使用StackOverflow。

这是我的代码

import java.io.File;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.lang.ArrayIndexOutOfBoundsException;

public class Coma {

public static void main(String[] args)throws IOException {
    // TODO Auto-generated method stub
    String SENTENCE;
    int NUM_LINES;
    Scanner sc= new Scanner(new File("coma.in"));
    NUM_LINES=sc.nextInt();

    for(int i=0;i<NUM_LINES;i++){
        SENTENCE=sc.nextLine();
        String [] temp;
        String delimiter=" ";
        temp=SENTENCE.split(delimiter);
        String year= temp[0];
        String word=temp[1];

        System.out.println("Nurse: Sir you've been in a coma since " + year     + "\nMe: How's my favorite " + word + " doing?");
    }
}

} 

这是来自文件coma.in

的输入
3
1495 Constantinople
1962 JFK
1990 USSR

3 个答案:

答案 0 :(得分:1)

问题很可能与您的coma.in文件格式有关。 但是,假设一个正确的文件格式如下:

  

<强> data.txt中

     

20队

     

10只狗

您可以将代码简化为:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("data.txt"));
        // default delimiter is whitespace (Character.isWhitespace)
        while (sc.hasNext()) { // true if another token to read
             System.out.println("Nurse: Sir you've been in a coma since "
                     + sc.next() + "\nMe: How's my favorite "
                     + sc.next() + " doing?");
        }
    }

}

答案 1 :(得分:1)

假设您的文件格式如下:

2
1981 x
1982 y

然后

sc.nextInt();  // only moves sc past the next token, NOT beyond the line separator

只会阅读2并在那里停止,而 NOT 会消耗换行符!因此,为了读取下一行(1981 x),您必须添加另一个sc.nextLine()以实际消耗2之后的(空)字符串以便到达下一行。然后,您将拆分空字符串,而空字符串又会导致ArrayIndexOutOfBoundsException,因为结果数组的长度只有1

//...
NUM_LINES=sc.nextInt();
sc.nextLine();  // add this line; 

for(int i=0;i<NUM_LINES;i++){
    SENTENCE=sc.nextLine();
    //...

由于nextIntnextFloat的这种行为。等方法,我倾向于使用nextLineparse...方法:

NUM_LINES=Integer.parseInt(sc.nextLine().strip()); 

答案 2 :(得分:1)

您可以替换:

NUM_LINES=sc.nextInt();

by:

NUM_LINES=Integer.valueOf(sc.nextLine());

它会正常工作。

相关问题