Question:
I am looking for a way to populate three different arrays from the contents of a file that has three columns of integers.
Answer:
Scanner(), StringTokenizer() and Integer.parseInt()
Code:
import java.io.*; import java.util.*; public class ScanFileContents { public static void main(String[] args)throws IOException { String[] columns = new String[3]; Scanner input; String str; StringTokenizer tokens; // need to know ho big of an array to create int lines = 0; input = new Scanner(new File("data.txt")); while(input.hasNext()){ str = input.nextLine(); lines = lines+1; } input.close(); int[] row1 = new int[lines-1]; int[] row2 = new int[lines-1]; int[] row3 = new int[lines-1]; input = new Scanner(new File("data.txt")); str = input.nextLine(); tokens = new StringTokenizer(str); columns[0]=tokens.nextToken(); columns[1]=tokens.nextToken(); columns[2]=tokens.nextToken(); int count = 0; while(input.hasNext()){ str = input.nextLine(); tokens = new StringTokenizer(str); row1[count] = Integer.parseInt(tokens.nextToken()); row2[count] = Integer.parseInt(tokens.nextToken()); row3[count] = Integer.parseInt(tokens.nextToken()); count = count + 1; } System.out.println(columns[0] + ":" + Arrays.toString(row1)); System.out.println(columns[1] + ":" + Arrays.toString(row2)); System.out.println(columns[2] + ":" + Arrays.toString(row3)); } }
Output:
$ java ScanFileContents TOM:[100, 77, 100, 89, 91, 95, 84, 92] BOB:[65, 78, 89, 66, 75, 78, 82, 93] JOHN:[33, 98, 44, 86, 85, 68, 44, 100] $ cat data.txt TOM BOB JOHN 100 65 33 77 78 98 100 89 44 89 66 86 91 75 85 95 78 68 84 82 44 92 93 100