In: Computer Science
Java - Text File to Arrays and output
------------------------------------------------------------------------------
I need to have a java program read an "input.txt" file (like below) and store the information in an respective arrays. This input.txt file will look like below and will be stored in the same directory as the java file. The top line of the text represents the number of people in the group for example. the lines below it each represent the respective persons preferences in regards to the other people in the group. I would then like the java program to output as a string each array and its elements.
Example of "input.txt" that would be read
4
2 3 4
1 3 4
1 2 4
1 2 3
As you can see the top line says there are 4 people in this group and person #1 which is line #2 prefers to be in a group with persons 2, 3, and 4 respectively. So for Person #1 it would be an Array with 3 elements being 2, 3, and 4 in that order.
The java program in this case would read the .txt file. create 4 arrays based on line #1 saying there are 4 people and then it would output as a string the 4 arrays and their respective elements in order,
Example Output:
Person #1 prefers 2, then 3, then 4
Person #2 prefers 1, then 3, then 4
.
.
.
The java program should be able to work with text files that have different numbers of people, it should create # of arrays based on the number on line 1.
Program in java:
//importing required package
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
//declaring class
public class ReadingTextFile {
//declaring main method
public static void main(String[] args) throws
FileNotFoundException, IOException {
//declaring the
variables
String line;
int size;
//creating file reader with
specified file
FileReader fr=new
FileReader("input.txt");
BufferedReader br=new
BufferedReader(fr);
//reading the file and
storing in the variable
StringTokenizer
stk;
size=Integer.parseInt(br.readLine().trim());
int person[][]=new
int[size][size-1];
int len=0;
//reading files
while((line=br.readLine())!=null){
stk=new StringTokenizer(line," ");
for(int i=0;i<size-1;i++){
//storing the value in the array
person[len][i]=Integer.parseInt(stk.nextToken());
}
len++;
}
//printing the content
of array
for(int
i=0;i<size;i++){
System.out.print("Person #"+(1+1)+" prefers ");
for(int j=0;j<size-1;j++){
System.out.print(person[i][j]+" then ");
}
//going to new Line
System.out.println();
}
}
}
Output;