In: Computer Science
Java Programming:
Scan a file and set up 3 different arrays from scanning through the .txt file. you should have 2 string arrays and 1 integer array.
I need help knowing how to read the file so that it puts the correct information into an array. It is all separated by spaces.
.txt file:
S SABQ138 3
A AABQ205 2
S SABQ127 1
A AABQ313 2
S SABQ126 2
A AABQ302 2
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new java program with name "Main.java" is created, which contains following code.
Main.java :
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
//Java class
public class FileReader {
//main method
public static void main(String[] args) throws
IOException {
// creating array of Strings
String[] strArray1 = new
String[6];
String[] strArray2 = new
String[6];
// creating array of integer
int[] intArray = new int[6];
FileInputStream fstream = new
FileInputStream("sample.txt");
BufferedReader br = new
BufferedReader(new InputStreamReader(fstream));
String strLine;
int i = 0;// declaring variable
i
// declaring a new array to split
file
while ((strLine = br.readLine()) !=
null) {
String[]
newArray = strLine.split(" ");// Splitting each line based on
space
strArray1[i] =
newArray[0];// storing 0th element in strArray1
strArray2[i] =
newArray[1];// storing 1st element in strArray2
intArray[i] =
Integer.parseInt(newArray[2]);// storing 2nd element in
intArray
i++;// increment
value of i
}
// print array elements
System.out.println("strArray1
elements : ");
for (i = 0; i <
strArray1.length; i++) {
System.out.print(strArray1[i] + " ");// print each array
element
}
System.out.println("\nstrArray2
elements : ");
for (i = 0; i <
strArray2.length; i++) {
System.out.print(strArray2[i] + " ");// print each array
element
}
// print intArray elements
System.out.println("\nintArray
elements : ");
for (i = 0; i < intArray.length;
i++) {
System.out.print(intArray[i] + " ");// print each array
element
}
}
}
======================================================
Output : Compile and Run above program to get the screen as shown below
Screen 1 :Main.java
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.