2016-11-12 60 views
0

因此,我的代码应该在输入文件中查看它包含的字符串,在有空格的地方将它们分开,然后分别输出字符串。我试着用一个数组来指派我分裂变量的字符串,这样的方式,当我想打印出来,但我不断收到我可以访问它们,从数组的索引中检索字符串,但它不起作用

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 
+0

你确定'temp'拥有多个元素吗?你应该首先检查'split'调用实际上是否分割了一些东西(并且不返回一个大小为1的数组) – UnholySheep

+0

问题在于你的输入数据 – developer

+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

假设你的文件格式是某事像:

2 
1981 x 
1982 y 

然后

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

将只读取2和立即停止,并消费一行!因此,为了读取下一行(1981 x),您必须添加另一个sc.nextLine()以实际使用2之后的(空)字符串才能到达下一行。然后您可以拆分空字符串这反过来又导致ArrayIndexOutOfBoundsException作为结果数组只是长度1的:由于对nextIntnextFloat这种行为的

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

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

。等方法,我倾向于使用nextLineparse...方法偏爱:

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

您可以更换:

NUM_LINES=sc.nextInt(); 

由:

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

它会正常工作。