I am writing a Java program to practice my programming skill. The program is supposed to read input from a file, split it using space, and then print it out.
import java.io.*;
import java.util.*;
public class SumsInLoopTester {
public static void main(String[] args) {
try
{
File f = new File("SumsInLoop.txt");
Scanner sc = new Scanner(f);
int n = sc.nextInt();
int i = 0;
int sum[] = new int[n]; // I will use this later
while(sc.hasNextLine())
{
String input = sc.nextLine();
String splits[] = input.split("\\s+");
System.out.println(splits[0]);
System.out.println(splits[1] + "\n");
}
} catch(FileNotFoundException e) {
System.out.println(e);
}
}
}
Here is what's inside the input file: SumsInLoop.txt
The output I expect to see is:
761892 144858
920553 631146
. . . .
. . . .
But instead, I got ArrayIndexOutofBoundsException exception. I tried to add space after each number on the second column and it worked. But I'm just curious why it wouldn't work without adding spaces. I spent so much time trying to figure this out, but no clue. I know that I don't have to split the string before I output it. Just want to have a little practice with split() method and get to know it better.