How to read data from a text file into arrays in Java - java

I am having trouble with a programming assignment. I need to read data from a txt file and store it in parallel arrays. The txt file contents are formatted like this:
Line1: Stringwith466numbers
Line2: String with a few words
Line3(int): 4
Line4: Stringwith4643numbers
Line5: String with another few words
Line6(int): 9
Note: The "Line1: ", "Line2: ", etc is just for display purposes and isn't actually in the txt file.
As you can see it goes in a pattern of threes. Each entry to the txt file is three lines, two strings and one int.
I would like to read the first line into an array, the second into another, and the third into an int array. Then the fourth line would be added to the first array, the 5th line to the second array and the 6th line into the third array.
I have tried to write the code for this but can't get it working:
//Create Parallel Arrays
String[] moduleCodes = new String[3];
String[] moduleNames = new String[3];
int[] numberOfStudents = new int[3];
String fileName = "myfile.txt";
readFileContent(fileName, moduleCodes, moduleNames, numberOfStudents);
private static void readFileContent(String fileName, String[] moduleCodes, String[] moduleNames, int[] numberOfStudents) throws FileNotFoundException {
// Create File Object
File file = new File(fileName);
if (file.exists())
{
Scanner scan = new Scanner(file);
int counter = 0;
while(scan.hasNext())
{
String code = scan.next();
String moduleName = scan.next();
int totalPurchase = scan.nextInt();
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}
}
}
The above code doesn't work properly. When I try to print out an element of the array. it returns null for the string arrays and 0 for the int arrays suggesting that the code to read the data in isn't working.
Any suggestions or guidance much appreciated as it's getting frustrating at this point.

The fact that only null's get printed suggests that the file doesn't exist or is empty (if you print it correctly).
It's a good idea to put in some checking to make sure everything is fine:
if (!file.exists())
System.out.println("The file " + fileName + " doesn't exist!");
Or you can actually just skip the above and also take out the if (file.exists()) line in your code and let the FileNotFoundException get thrown.
Another problem is that next splits things by white-space (by default), the problem is that there is white-space on that second line.
nextLine should work:
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.parseInt(scan.nextLine());
Or, changing the delimiter should also work: (with your code as is)
scan.useDelimiter("\\r?\\n");

You are reading line so try this:
while(scan.hasNextLine()){
String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = Integer.pasreInt(scan.nextLine().trim());
moduleCodes[counter] = code;
moduleNames[counter] = moduleName;
numberOfStudents[counter] = totalPurchase;
counter++;
}

String code = scan.nextLine();
String moduleName = scan.nextLine();
int totalPurchase = scan.nextInt();
scan.nextLine()
This will move scanner to proper position after reading int.

Related

The content of my text file is not showing when I run the program

I'm trying to read the contents of a text file and print them. I cannot figure out why the content is not displayed when I run the program.
This is my code:
import java.io.*;
import java.util.Scanner;
public class ReadTxtfile{
public static void main (String [] args) throws IOException{
Scanner input = new Scanner(System.in);
//Open the file
File file = new File("chessfile.txt");
//Open files for reading
Scanner inputFile = new Scanner(file);
while(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
//Read lines from the file
while(inputFile.hasNext());
//Read next
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
//Display File
System.out.printf(piece, color, column, row);
//Close file
inputFile.close();
}
}//End of main
A few things first you dont want to loop while the file exists and then use system.exit if you really need to just use an if statement
if(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
Second your going to want to use file.hasNextLine() instead of hasNext and also where are the curly braces for your loop this is what it should look like.
while(inputFile.hasNextLine()){
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
}
Finnnaly i guess with printf your trying to display them neatly well you cant do that outside of the loop so instead of doing all that nonsense create a String array and store each of the lines in that as you get the different values. Assuming that your data is on seperate lines it should look somewhat like this.
ArrayList<String> peices = new ArrayList<String>();
while(inputFile.hasNextLine()){
String peice = "";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peices.add(peice);
}
And finnaly to display them on multiple lines you should use a simple enhanced loop.
for(String i : peices) {
System.out.println(i);
}
your while loop is not working. so next line data not coming in a string object.
and if you want getting all your text file data in one line try below loop.
String line ="";
while(scanner.hasNextLine())
line += scanner.nextLine();
System.out.printf(line );

How to convert a text file to array object? Java

I am working on a program that takes in a text file and converts it to a team roster. The text file has unknown length, first name, last name, offence score, and defense score. the name and scores are on the same line. Rachael Adams 3.36 1.93. I can not figure out how to convert each line of the text file into an object. I've searched the internet and all of the examples just have one value per a line and converts it into one big array. I've included some extra imports in the code because i know that I will need them further on in the project(find best attackers, best defenders, make teams of 6, print teams). I've modified code from previous projects that took in numbers separated by lines.
class VolleyballFile {
String fileName;
int count;
String currentFileName;
String outputFile="";
String firstName;
String lastName;
double attackScore;
double defenceScore;
Scanner input = new Scanner(System.in);
public VolleyballFile() throws FileNotFoundException {
System.out.println("Please enter a file name to get the roster from");
this.fileName = input.nextLine();
File file = new File(fileName);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()){
int result = Integer.parseInt(scan.nextLine());
this.count+=1;
}
}
}
Using the command String.split(); you can split a string up to an array of strings. So:
while (scan.hasNextLine()) {
//int result = Integer.parseInt(scan.nextLine());
string[] line = scan.nextLine().split(" ");
firstName = string[0];
lastName = string[1];
attackScore = Float.Parse(string[2]);
defenceScore = Float.Parse(string[3]);
this.count+=1;
}
I'm not sure if you can Float.Parse(), don't remember since I haven't used java recently.

Read data from file and convert to key value pair

I have the below integers in File :
758 29
206 58
122 89
I have to read these integers in an integer array and then need to store the values in key value pair. Then print the output as :
Position 29 has been initialized to value 758.
Position 89 has been initialized to value 122.
I have tried as of now :
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename);
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
String[] line = intStringSplit.split("\t",-1);
data = new int[line.length];
for (int i = 0; i < data.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println(data);
}
linReader.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
return linReader;
}
I am not able to figure out how to get the key and value from the read data.
When posting information related to your question it is very important that you provide the data (in file for example) exactly as it is intended in reality so that we can make a more positive determination as to why you are experiencing difficulty with your code.
What you show as an in file data example indicates that each file line (which contains actual data) consists of two specific integer values. The first value being the initialization value and the second being the position value.
There also appears to be a blank line after ever line which contains actual data. This really doesn't matter since the code provided below has a code line to take care of such a thing but it could be the reason as to why you may be having difficulty.
To me, it looks like the delimiter used to separate the two integer values in each file line is indeed a whitespace as #csm_dev has already mentioned within his/her comment but you claim you tried this in your String.split() method and determined it is not a whitespace. If this is truly the case then it will be up to you to determine exactly what that delimiter might be. We couldn't possibly tell you since we don't have access to the real file.
You declare a File object within your provided code but yet nowhere do you utilize it. You may as well delete it since all it's doing is sucking up oxygen as far as I'm concerned.
When using try/catch it's always good practice to catch the proper exceptions which in this case is: IOException. It doesn't hurt to also display the stack trace as well upon an exception since it can solve a lot of your coding problems should an exception occur.
This code should work:
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename); // why do you have this. It's doing nothing.
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
// If the file line is blank then just
// continue to the next file line.
if (intStringSplit.trim().equals("")) { continue; }
// Assuming at least one whitespace is used as
// the data delimiter but what the heck, we'll
// use a regular expression within the split()
// method to handle any number of spaces between
// the integer values.
String[] line = intStringSplit.split("\\s+");
data = new int[line.length];
for (int i = 0; i < line.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println("Position " + data[1] +
" has been initialized to value " +
data[0] + ".");
// do whatever else you need to do with the
// data array before reading in the next file
// line......................................
}
linReader.close();
}
catch (IOException ex) {
System.out.println("File Not Found");
ex.printStackTrace();
}
return linReader;
}

Reading a file of txt to be fed into an array

Here a user enters a list of 1's and 0's.... so an input would 10001010. However I want it to read from a text file... my text file input.txt also containes 10001010... need the coverDataArray array to be fed the same string from the console as from a file.
I tried Datainput stream however, it throws me the exception
'
Scanner in = new Scanner (System.in);
String data1="";
...
.....
try{
System.out.println("Enter the binary bits");
data1 = in.next();
for ( int i = 0; i < data1.length(); i++)
{
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
}'
You can pass a File Object instead of System.in to Scanner constructor. Try it as shown below:
String fileName = "input.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
String s = "";
while(scanner.hasNextLine()){
s = scanner.nextLine();
// your code. You can also use scanner.next() to read word by word instead of nextLine()
}
Byte.parseByte(data1.substring( i, i+1));
Your exception is caused by the fact that you're going up to length - 1, then length - 1 + 1, which is length, which is goign to cause your ArrayOutOfBoundsException. This can be seen on this line:
covertDataArray[i] = Byte.parseByte(data1.substring( i, i+1));
At one point, i is equal to length-1, or the last index in your String. You then attempt to access the next element, which doesn't exist.
And as for your file, you can pass a File object into the Scanner.
Example
Either..
File file = new File("yourfile.txt");
Scanner s = new Scanner(file);
You are trying to use Byte.parseByte as a methode of parsing binairy input, this doesn't really work as parseByte will try to take a numerical input and parse it into a number between -128 and 127. You should use a different method.

removeAll operation on arraylist makes program hang

I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas.
I read each file with the following code (not complete):
ArrayList<String> temp = new ArrayList<>();
FileInputStream fis;
fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
scan.close();
return temp;
Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.
I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:
public static ArrayList differentWords(String fileName1, String fileName2) {
ArrayList<String> file1 = readFile(fileName1);
ArrayList<String> file2 = readFile(fileName2);
file1.removeAll(file2);
return file1;
}
My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?
You are not using input in
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
I think you meant to do this:
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (input.hasNext()) {
String md5 = input.next();
temp.add(md5);
}
}
but that said you should look into String#split() that will probably save you some time:
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split(",");
for (String token: tokens) {
temp.add(token);
}
}
try this :
for(String s1 : file1){
for(String s2 : file2){
if(s1.equals(s2)){file1.remove(s1))}
}
}

Categories