Hi I am working on JAVA project and need help with inputing a text file into an
ID: 3676126 • Letter: H
Question
Hi I am working on JAVA project and need help with inputing a text file into an array. I have a .txt file that looks like this (the code should work with any .txt file that looks like this but varying in length):
819283761,112211324135412
834987341,222121324135211
899991828,112211324135421
888181818,212111313124412
892823736,111111111111111
I need to call a method to insert this file into an array. The integers on the left are Student ID numbers and the integers on the left are test answers. I'm not sure if how to get read these and store them into a 2D array. some help would awesome. Thanks
Explanation / Answer
import java.io.File;
import java.util.Scanner;
/**
* @author srinu
*
*/
public class ReadData {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("a.txt"));
String[][] data = readData(scanner);
for (int i = 0; i < data.length; i++) {
System.out.println("Student ID:" + data[i][0]
+ " Student Answers :" + data[i][1]);
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* @param scanner
* @return
*/
public static String[][] readData(Scanner scanner) {
String[][] data = new String[5][2];
int i = 0;
while (scanner.hasNext()) {
String line = scanner.nextLine();
data[i][0] = line.split(",")[0];
data[i][1] = line.split(",")[1];
i++;
}
return data;
}
}
a.txt:
819283761,112211324135412
834987341,222121324135211
899991828,112211324135421
888181818,212111313124412
892823736,111111111111111
OUTPUT:
Student ID:819283761 Student Answers :112211324135412
Student ID:834987341 Student Answers :222121324135211
Student ID:899991828 Student Answers :112211324135421
Student ID:888181818 Student Answers :212111313124412
Student ID:892823736 Student Answers :111111111111111