Create Multiple Arrays from a text file
Hi,
I am having trouble creating multiple arrays from each line in a text file. This is my text file:
2 8 8
3 6 9
3 1 7
I am able to read this file in, create tokens and print all the values. My goal now is to create 3 arrays from this file. Array1 = [2, 8, 8], Array2 = [3, 6, 9], and Array3 = [3, 1, 7]
This is my code so far. Please let me know if you can help or direct me to a good link online.
Thanks, Chris
import java.io.*;
import java.util.StringTokenizer;
public class Project1 {
public static void createArrays(){
int[] nums = null;
try {
File file1 = new File("file1.txt");
FileReader fileReader = new FileReader(file1);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
StringTokenizer st = new StringTokenizer (line);
while (st.hasMoreTokens()){
String token = st.nextToken();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String [] args){
createArrays();
}
}
Re: Create Multiple Arrays from a text file
Code :
import java.io.*;
import java.util.StringTokenizer;
public class Project1 {
public static void createArrays(){
int[] nums = null;
try {
File file1 = new File("file1.txt");
FileReader fileReader = new FileReader(file1);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line = reader.readLine()) != null){
StringTokenizer st = new StringTokenizer (line);
nums = new int[st.countTokens()];
//System.out.println(line);
int i=0;
while (st.hasMoreTokens()){
String token = st.nextToken();
nums[i] = Integer.parseInt(token);
i++;
}
System.out.print("[");
for(int j=0;j<i;j++){
System.out.print(" "+nums[j]+" ");
}
System.out.println("]");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String [] args){
createArrays();
}
}
i feel this code will help you to move further.