How to convert a text file to array object? Java - 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.

Related

Why do I get an ArrayIndexOutOfBoundsException with this?

Hey there pretty new to Java I have a CSV file that I am scanning line by line (I am assuming) and printing out the details formatted. I keep getting a java.lang.ArrayIndexOutOfBoundsException: 1 what could I be doing wrong?
Here is the CSV file contents.
1,Mazda CX-9,7,Automatic,Premium,150
2,VW Golf,5,Automatic,Standard,59
3,Toyota Corolla,5,Automatic,Premium,55
4,VW Tiguan,7,Automatic,Premium,110
5,Ford Falcon,5,Manual,Standard,60
String fileName = "CarList.CSV";
File file = new File(fileName);
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
carsAvailableCount++;
String line = input.nextLine();
int lenght = line.length();
String fields[] = line.split(",");
String carNo = fields[0];
String carName = fields[1];
String seats = fields[2];
String transmission = fields[3];
String carType = fields[4];
String rate = fields[5];
System.out.format("%-9s%-9s%-9s%-9s%-9s%-9s\n", carNo, carName, seats, transmission, carType, rate);
}
Figured out the problem haha, my CSV file had empty lines below my last entry. Cheers everyone.

Read mixed types of data from a file with Java

I am a bit stuck with this code. I have file file name.txt which contains following data:
BD1 // user ID
Bob Dillon // user full name
user#email.com // user Email
10.0 // amount of cash
100 // No.of Points
I can't read first and last name of user in the same string. Here is my code:
Scanner input_File = new Scanner(new File("customer.txt"));
int num_Customers = 0;
while(input_File.hasNext() && num_Customers < maxLoyalty_CardsQty)
{
//read ID
customerID[num_Customers] = input_File.next();
input_File.nextLine();
//Here is my problems begins
while(input_File.hasNextLine())
{
String line = input_File.nextLine();
Scanner line_Scan = new Scanner(line);
line_Scan.useDelimiter(" ");
fName[num_Customers] = input_File.next();
lName[num_Customers] = input_File.next();
line_Scan.close();
}
//read Email
email[num_Customers] = input_File.next();
//read Cash
spendToDate[num_Customers] = input_File.nextDouble();
//read Points
points[num_Customers] = input_File.nextInt();
num_Customers++;
}
input_File.close();
Consider using different data layout in the file. It's easier if you have all the required data in a single line, e.g. comma separated especially if you have information about multiple users (and I guess that's the case)
FS1, FirstName, LastName, foo#bar.baz, 10.0, 100
Then you can go with something like this
Scanner scanner = new Scanner(new File("customer.txt"));
while (scanner.hasNext()) {
String[] splitted = scanner.nextLine().split(", ");
// then you've data in a nice array arranged like below
// splitted[0] = user Id
// splitted[1] = first name
// etc.
fName[numCustomers] = splitted[1];
// ...
spendToDate[numCustomers] = splitted[3];
}
Or you can use Java 8 to simplify this to:
new Scanner(new File("customer.txt"))
.forEachRemaining(line -> {
String[] splitted = line.split(", ");
// etc.
});
or to:
Files.lines(Paths.get("customer.txt"))
.forEach(line -> {
String[] splitted = line.split(", ");
// splitted[0] = user Id
// splitted[1] = user name and surname
// etc.
});
Also, a friendly advice, make yourself acquainted with Java's naming conventions it'd make your code much cleaner and easier to read.

Reading a .csv file using scanner

I am working on a project that involves asking a user for their zip code. Using the zip code provided the program should loop through a .csv file to determine what city they live in. I can read the information in the .csv file but I have no idea how to loop through it to find a specific piece of information.
import java.util.Scanner;
import java.io.*;
public class DetermineCity {
public static void main(String[] args) throws IOException {
String zip = "99820,AK,ANGOON";
Scanner keyboard = new Scanner(System.in);
System.out.println("enter then name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is ");
System.out.println(line);
inputFile.close();
}
}
Use Scanner.hasNext() method to loop
String Details="";
int ZipCodeIndex=0;
String ZipCode = "10230"
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext()){
String x=inputFile.nextLine();
String[] arr=x.split(",");
if(ZipCode.equals(arr[ZipCodeIndex]))
{
Details=x;
break;
}
}
This assumes the format of your file is of the form "2301,Suburb, City, Country"
the .nextLine() function returns a String of the next line, however return null if their isn't a line. So using a while loop you can go through your file and store each line in a string.
Then using .split() method you would break this string using a delimiter ",". This would be stored in an array.
Then compare the user zip code with the first value of the array. If they match then you have an array with the city and other information. Then a break statement as you have found the city.
String suburb;
String[] lineArray;
String line = null;
while((line = inputFile.nextLine()) != null){
lineArray[] = line.split(",");
if(lineArray[0] == zipCodeString){
suburb = lineArray[1];
break;
}
}

How to create an array of objects that have strings from a CSV file of strings?

I have some code that reads from a csv file that is full of the last name, first name, and birth year of a lot of people. It looks like this in the csv file:
nameLast nameFirst birthYear
Santos Valerio 1972
Tekulve Kent 1947
Valentine Fred 1935
I have a class called Human, and the human class also has these three values. I would like to create an array of the human class, and pass into it all of my data from the csv file. That way, if the first instance of the array at [0] will have three values in it, two for the names and one for the year. Here is the code I have so far:
package testing.csv.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Human {
String lastName;
String firstName;
String birthYear;
public static void main(String[] args) {
//.csv comma separated values
String fileName = "C:/Users/Owner/Desktop/Data.csv";
File file = new File(fileName); // TODO: read about File Names
try {
Scanner inputStream = new Scanner(file);
inputStream.next(); //Ignore first line of titles
while (inputStream.hasNext()){
String data = inputStream.next(); // gets a whole line
String[] values = data.split(",");
System.out.println(values[2]);
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What I have here will currently print out all of the birth years, since values[2] is the birth year. I thought that I could change the line
String[] values = data.split(",");
To read
Human[] values = data.split(",");
And then it would automatically assign the values lastName, firstName, and birthyear into the right places for every object in the array. However, doing this just produces the error message
incompatible types: String[] cannot be converted to Human[]
I tried also changing the line above this one from
String data = inputStream.next(); // gets a whole line
to
Human data = inputStream.next(); // gets a whole line
but I get the same error message.
So what am I doing wrong? Perhaps I didn't properly define the class as I thought I did, or is there something much more wrong with my approach? Please let me know what you think.
First of all, your Human class needs a constructor. Insert the following method.
public Human(String[] str) {
lastName = str[0];
firstName = str[1];
birthYear = str[2];
}
Now, instead of a string array, you can get a Human object using
Human someHuman = new Human(data.split(","));
The method split in class String returns an array of Strings, not an array of Human. To create an array of Human, you'll need to parse that String array returned from split into the values human needs.
class Human{
String firstName;
String lastName;
int birthYear;
public Human(String first, String last, int birthYear){
this.firstName = first;
this.lastName = last;
this.birthYear = birthYear;
}
}
int numHumansInCSV = //How many humans are in your file?
Human[] humanArray = new Human[numHumansInCSV];
int index = 0;
while (inputStream.hasNext()){
String data = inputStream.next(); // gets a whole line
String[] values = data.split(",");
String lastName = values[0];
String firstName = values[1];
int birthYear = Integer.parseInt(values[2]);
Human human = new Human(firstName, lastName, birthYear);
//put human in human array.
humanArray[index] = human;
index += 1;
}
If you can use a datastructure like List, that'd be more appropriate than an array as you might not know how many humans your CSV file contains.
Also, this parsing code should really be in its own class. If I were writing this, here's what I'd do.
public class HumanCSVReader{
public List<Human> read(String csvFile, boolean expectHeader) throws IOException{
File file = new File(csvFile);
Scanner scanner = new Scanner(file);
int lineNumber = 0;
List<Human> humans = new List<Human>();
while(scanner.hasNextLine()){
if(expectHeader && lineNumber==0){
++lineNumber;
continue;
}
String line = scanner.nextLine();
String csv = line.split(",");
if(csv.length!=3)
throw new IOException("Bad input in "+csvFile+", line "+lineNumber);
String firstName = list[0];
String lastName = list[1];
try{
int birthYear = Integer.parseInt(list[2]);
}catch(NumberFormatException e){
throw new IOException("Bad birth year in "+csvFile+", line "+lineNumber);
}
Human human = new Human(fistName, lastName, birthYear);
humans.add(human);
++lineNumber;
}
return humans;
}
}
Just use this to load in your array of humans instead. It'll even handle some basic validation.

How to read data from a text file into arrays in 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.

Categories